解题思路
遍历要判断的字符串,找到第一个有可能的字母,然后从此的下一位开始对比,如果各位均对应相等则直接return出
这个字母的位置,注意空串的输出为0,其余情况均为-1;
typedef unsigned long long ULL;
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.size() == 0) return 0;
int p = 131;
vector<ULL> P(haystack.size() + 1);
vector<ULL> S(haystack.size() + 1);
P[0] = 1;
S[0] = 0;
for(int i = 0; i < haystack.size(); i ++){
P[i + 1] = P[i] * p;
S[i + 1] = S[i] * p + haystack[i];
}
ULL nee = 0;
for(auto x:needle) nee = nee * p + x;
for(int i = 1; i + needle.size() - 1 <= haystack.size(); i ++){
if(S[i + needle.size() - 1] - S[i - 1] * P[needle.size()] == nee) return i - 1;
}
return -1;
}
};