问题:
Implement strStr()
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
分析:效率最高的是KMP算法,但是不容易实现,所以先写了一个传统的字符串匹配算法。
解决办法:
//解决办法1:传统字符串匹配算法
//时间复杂度O(nm),空间复杂度O(1)
class Solution {
public:
int strStr(string haystack, string needle) {
int i, j;
for (i = 0, j = 0; i < haystack.size() && j < needle.size(); ) {
if (haystack[i] == needle[j]) {
++i; ++j;
} else {
i = i - j + 1;
j = 0;
}
}
return j == needle.size() ? i - j : -1;
}
};
//KMP算法
//时间复杂度O(n+m),空间复杂度O(1)
class Solution {
public:
int strStr(string haystack, string needle) {
//要考虑到当needle为""的情况
if (needle == "") {
return 0;
}
else {
vector<int>next(needle.size());
getNext(needle, next);//获取next数组,保存到vector中
int i = 0, j = 0;
while(i != haystack.size() && j != needle.size()) {
if (j == -1 || haystack[i] == needle[j]) {
++i; ++j;
}
else {
j = next[j];
}
}
return j == needle.size() ? i - j: -1;
}
}
void getNext(string p, vector<int> &next) {
next[0] = -1;
int i = 0, j = -1;
while (i != p.size() - 1) {
//这里注意,i==0的时候实际上求的是next[1]的值,以此类推
if (j == -1 || p[i] == p[j]) {
++i;
++j;
next[i] = j;
} else {
j = next[j];
}
}
}
};