首页 > 代码库 > LeetCode--Implement strStr()
LeetCode--Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
KMP算法的应用
class Solution { public: int strStr(char *haystack, char *needle) { if(haystack == NULL) return -1; string hs=""; string ns=""; int n=0; int m=0; while(haystack[n] != '\0') { hs += haystack[n]; n++; } if(needle == NULL) return -1; while(needle[m] != '\0') { ns += needle[m]; m++; } if( m==0 && n==0) return 0; if(n==0) return -1; if(m==0) return 0; if(m>n) return -1; int* next = new int[m]; get_next(needle,next,m); int i=0,j=0; while(i<n && j<m) { if(j<0 || hs[i] == ns[j]) { i++; j++; } else j = next[j]; } if(j==m) return i-j; else return -1; } void get_next(char* needle, int* next, int n) { int i=1; next[0] = -1; while(i<n) { int k = next[i-1]; while(k>=0 && needle[k] != needle[i-1]) k = next[k]; if(k<0) next[i] = 0; else next[i] = k+1; i++; } } };
LeetCode--Implement strStr()
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。