LeetCode28 找出字符串中第一个匹配项的下标
题目链接:找出字符串中第一个匹配项的下标
思路
本题考察到了KMP算法,重点在于求next数组。考研时只学会用模式串移动的手算方法求next数组,对于严书中的前后缀做法比较陌生,看了代码随想录的文章和视频才理解,勉强掌握。而且关于next数组有很多种,常见的是将前缀表减一”:右移一位,初始位置为-1;也可以直接将前缀表用来当作next数组,都可以实现next数组,原理上无差别,本题使用前者。关于具体next数组的讲解可见上述文章视频。
代码
class Solution {
public:
//该next数组为前缀表统一减一(右移一位,初始位置为-1)
void getNext(int* next, const string& s) {
int j = -1;
next[0] = j;
for (int i = 1; i < s.size(); i++) {
while (j >= 0 && s[i] != s[j + 1]) { // 前后缀不相同,回退
j = next[j];
}
if (s[i] == s[j + 1]) { // 相同前后缀
j++;
}
next[i] = j; // 将j(前缀长度)赋给next[i]
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
int next[needle.size()];
getNext(next, needle);
int j = -1; // next数组里记录的起始位置为-1
for (int i = 0; i < haystack.size(); i++) {
while (j >= 0 && haystack[i] != needle[j + 1]) { // 不匹配,j回退
j = next[j];
}
if (haystack[i] == needle[j + 1]) { // 匹配,同时后移
j++;
}
if (j == (needle.size() - 1)) {
return (i - needle.size() + 1);
}
}
return -1;
}
};
总结
时间复杂度O(m+n)
空间复杂度O(m) m为needle长度
Leetcode459 重复的子字符串
题目链接:重复的子字符串
思路
本题仍使用KMP算法,根据最长相等前后缀的规则,当一个字符串由重复子串组成的,最长相等前后缀不包含的子串就是最小重复子串。数学推导见文章
代码
class Solution { //前缀表统一减一的方式
public:
void getNext (int* next, const string& s){
next[0] = -1;
int j = -1;
for(int i = 1;i < s.size(); i++){
while(j >= 0 && s[i] != s[j + 1]) {
j = next[j];
}
if(s[i] == s[j + 1]) {
j++;
}
next[i] = j;
}
}
bool repeatedSubstringPattern (string s) {
if (s.size() == 0) {
return false;
}
int next[s.size()];
getNext(next, s);
int len = s.size();
if (next[len - 1] != -1 && len % (len - (next[len - 1] + 1)) == 0) {
return true;
}
return false;
}
};
复杂度
时间复杂度O(n)
空间复杂度O(n)