<pre name="code" class="cpp">方法一:
/*暴力法*/
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.size() < needle.size()) return -1;
for(std::size_t i = 0; i < haystack.size() - needle.size() + 1; ++i){
std::size_t k = i, j = 0;
for(; j < needle.size(); ++j){
if(haystack[k++] != needle[j]) break;
}
if(j == needle.size()) return i;
}
return -1;
}
};
方法二:
/*KMP算法*/
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
if(haystack.size() < needle.size()) return -1;
vector<int> next;
get_next(needle, next);
int i = 0, j = 0;
while(i < (int)haystack.size() && j < (int)needle.size()){
if(j == -1 || haystack[i] == needle[j]){
++i;
++j;
}
else j = next[j];
}
return j == needle.size() ? i - needle.size() : -1;
}
void get_next(const string &s, vector<int> &next){
next.assign(s.size(), 0);
int i = 0, j = -1;
next[i] = j;
while(i < s.size()-1){
if(j == -1 || s[i] == s[j]){
++i;
++j;
next[i] = (s[i] == s[j] ? next[j] : j);
}
else j = next[j];
}
}
};
07-23
07-23
07-23
07-23