28. 实现 strStr() - 力扣(LeetCode)
简单题
暴力匹配
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
if(needle.size() > haystack.size()) return -1;
int i = 0, n = haystack.size(), m = needle.size();
while(i < n-m+1){
if(haystack[i] != needle[0] || haystack[i+m-1] != needle[m-1]){//先判断首尾是否相同
++i;
continue;
}
else if(haystack.substr(i, m) == needle) return i;
else ++i;
}
return -1;
}
};
其实这个方法虽然是暴力法,但是只要首先考虑首尾,最后效率会很快(比下面的都要快)。
KMP
关于kmp算法,可以看这儿:
数据结构与算法之美:34 | 字符串匹配基础(下):如何借助BM算法轻松理解KMP算法?_qq_32523711的博客-CSDN博客
class Solution {
public:
void getNexts(vector<int> &next, string &s, int m){
int k = -1; //最长匹配前缀字串末尾字符下标(-1代表不存在)
for(int i = 1; i < m; ++i){
while(k != -1 && s[k+1] != s[i])
k = next[k];
if(s[k+1] == s[i]) ++k;
next[i] = k;
}
}
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
vector<int> next(needle.size(), -1);
getNexts(next, needle, needle.size());
int j = 0;//在needle上遍历
for(int i = 0; i < haystack.size(); ++i){//在haystack上遍历
while(j > 0 && haystack[i] != needle[j]){// i 为坏字符
j = next[j-1]+1;//更新 j 的位置,继续从位置 i 开始匹配
}
if(haystack[i] == needle[j]) ++j;
if(j == needle.size()) return i-needle.size()+1;
}
return -1;
}
};
RK算法
介绍可以看:
数据结构与算法之美:32 | 字符串匹配基础(上):如何借助哈希算法实现高效字符串匹配?_qq_32523711的博客-CSDN博客
简单的哈希函数加上二次验证:
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size(), n = needle.size();
if(n == 0) return 0;
int hash_h = 0, hash_n = 0;
for(int i = 0; i < n; ++i){
hash_h += pow(haystack[i] - 'a', 2);
hash_n += pow(needle[i] - 'a', 2);
}
if(hash_h == hash_n && haystack.substr(0, n) == needle) return 0;//最开始就刚好匹配
for(int i = 1; i < m-n+1; ++i){//在haystack上遍历
hash_h = hash_h-pow(haystack[i-1]-'a',2) + pow(haystack[i+n-1]-'a', 2);
if(hash_h == hash_n)
if(haystack.substr(i, n) == needle) return i; //二次验证
}
return -1;
}
};