python 代码, 暴力匹配 和 Sunday 解法
class Solution:
def strStr00(self, haystack: str, needle: str) -> int: # 暴力求解
m, n = len(haystack), len(needle)
if n == 0:
return 0
elif n > m:
return -1
for i in range(m - n + 1):
if haystack[i] == needle[0]:
if haystack[i:i + n] == needle:
return i
continue
return -1
def strStr(self, haystack: str, needle: str) -> int: # Sunday 解法
if not needle: return 0
lnd, lnf = len(needle), len(haystack)
if lnd > lnf: return -1
dic = {v: lnd - k for k, v in enumerate(needle)} # 偏移表预处理
idx = 0
while idx + lnd <= lnf:
str_cut = haystack[idx:idx + lnd] # 待匹配字符串
if str_cut == needle: # 判断是否匹配
return idx
elif idx + lnd == lnf:
return -1
else: # 不匹配情况下,根据下一个字符的偏移,移动idx
nextc = haystack[idx + lnd]
idx += dic[nextc] if nextc in dic else lnd + 1
return -1
if __name__ == "__main__":
s = Solution()
haystack = "aaacaaab"
needle = "aaab"
res = s.strStr(haystack, needle)
print("res: ", res)
C++ 代码:Sunday 解法 和 KMP 解法
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
class Solution
{
public:
int strStr0(string haystack, string needle) // Sunday 解法
{
int hSize = haystack.size();
int nSize = needle.size();
if (nSize == 0)
return 0;
if (nSize > hSize)
return -1;
unordered_map<char, int> shift;
for (int i = 0; i < nSize; i++)
shift[needle[i]] = nSize - i; // 建立偏移表
int i = 0;
while (i <= hSize - nSize) // 遍历
{
if (haystack.substr(i, nSize) == needle)
{
return i;
}
else
{
if (i + nSize > hSize - 1)
return -1;
else
{
if (shift.find(haystack[i + nSize]) != shift.end())
{
i += shift[haystack[i + nSize]]; // 查询substr后的字符的偏移值
}
else
{
i += nSize + 1;
}
}
}
}
return -1;
}
int strStr(string haystack, string needle) // KMP 解法
{
int m = needle.size(), n = haystack.size();
if (m == 0)
{
return 0;
}
if (m > n)
{
return -1;
}
int next[m];
getNext(next, needle);
int j = 0;
for (int i = 0; i < n; i++)
{
while (j > 0 && haystack[i] != needle[j])
{
j = next[j - 1];
}
if (haystack[i] == needle[j])
{
j++;
}
if (j == m)
{
return (i - m + 1);
}
}
return -1;
}
private:
void getNext(int *next, const string &s) // 获得 模式串的 next 数组
{
int j = 0;
next[0] = 0;
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;
}
}
};
int main()
{
Solution sol = *new Solution();
string haystack = "aaaaaaab";
string needle = "aaab";
int res = sol.strStr(haystack, needle);
printf("res: %d\n", res);
return 0;
}
// 编译:g++ demo.cc -o demo
// 执行: ./demo
参考链接:
【1】简单学KMP算法
【2】Sunday解法