本题涉及到使用kmp算法,对字符串进行模式匹配,kmp算法可以参考代码随想录-kmp算法。
代码如下:
class Solution {
public:int strStr(string haystack, string needle) {vector<int> next = getNext(needle);int j = 0;for(int i = 0; i < haystack.size(); i++){while(j > 0 && haystack[i] != needle[j]){j = next[j - 1];}if(haystack[i] == needle[j]){j++;}if(j == needle.size()){return i - needle.size() + 1;}} return -1;}vector<int> getNext(string& s){int j = 0;vector<int> next(s.size());for(int i = 1; i < s.size(); i++){while(j > 0 && s[i] != s[j]){j = next[j - 1];}if(s[i] == s[j]){j++;}next[i] = j;}return next;}
};