问题描述
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.
分析
查找字符串needle在haystack第一次出现的位置索引。这里需要用到已匹配部分的历史信息,从而减少字符比较次数。举例:haystack:abcdabXXX,needle:abcdabXXX,这里我们可以利用的历史信息即为ab,这样下次开始比较时从ab开始匹配。
代码
这里m用来记录失败匹配时已匹配部分有多少无需再比较的部分的字符数,上述例子m=2.
//运行时间:8ms class Solution { public: int strStr(string haystack, string needle) { if (needle.empty()) return 0; int h_len = haystack.length(); int n_len = needle.length(); if (h_len < n_len) return -1; //int ans = haystack.find(needle, 0); //if (ans == string::npos) return -1; //return ans; int i = 0; int m = 0; int j = 0; bool flag = false; int ans; while (i < h_len){ ans = i - m; j = m; m = 0; while (i < h_len&&j < n_len&&haystack[i] == needle[j]){ if (j){ if (needle[j] == needle[m]) m++; else m = 0; } i++; j++; } if (j == n_len) { flag = true; break; } if (!j) i++; } if (flag) return ans; return -1; } };
时间: 2024-10-26 22:09:29