LeetCode28. 找出字符串中第一个匹配项的下标
文章链接:代码随想录
题目链接:28. 找出字符串中第一个匹配项的下标
思路:主要是学习KMP的应用(前缀表,也就是next数组的构建),另外感觉最后文本串和模式串的比较和前缀表的构建过程很相似。
20240225更:事实上,前缀表的构建过程就是用到了KMP的思想,在模式串自身上实现了。
另外在解释下对KMP的理解:
就是免去了暴力匹配中 不成功情况时 两个串(文本串指针位置加1,模式串指针挪到头)指针就都从头开始比的过程。
因为前缀表记录了模式串中每个字符前面部分有哪些子部分是相同的,所以除了可以直接将模式串指针直接挪动到重复位置外,相当于把文本串匹配的指针也挪动到了应有位置,省去了暴力匹配中无效匹配(挪动文本串指针)和重复匹配(从头挪动模式串指针)的过程。
文本串:长串
模式串:短串
前缀表减1版本:
class Solution {
public:
void getNext(int* next, string& s){
int j = -1;
next[0] = j;
for (int i = 1; i < s.size(); i++){
while (j >= 0 && s[j + 1] != s[i]){
j = next[j];
}
if (s[j + 1] == s[i]){
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0){
return 0;
}
int next[needle.size()];
getNext(next, needle);
int j = -1;
for (int i = 0; i < haystack.size(); i++){
while (j >= 0 && needle[j + 1] != haystack[i]){
j = next[j];
}
if (needle[j + 1] == haystack[i]){
j++;
}
if (j == needle.size() - 1){
return (i - needle.size() + 1);
}
}
return -1;
}
};
前缀表不减1版本:
class Solution {
public:
void getNext(int* next, string& s){
int j = 0;
next[0] = j;
for (int i = 1; i < s.size(); i++){
while (j > 0 && s[j] != s[i]){
j = next[j - 1];
}
if (s[j] == s[i]){
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0){
return 0;
}
int next[needle.size()];
getNext(next, needle);
int j = 0;
for (int i = 0; i < haystack.size(); i++){
while (j > 0 && needle[j] != haystack[i]){
j = next[j - 1];
}
if (haystack[i] == needle[j]){
j++;
}
if (j == needle.size()){
return (i - needle.size() + 1);
}
}
return -1;
}
};
LeetCode459.重复的子字符串
文章链接:代码随想录
题目链接:459.重复的子字符串
思路:也是KMP的应用,理解一下最小子字符串的判断方法就可以。
class Solution {
public:
void getNext(int* next, string& s){
int j = -1;
next[0] = j;
for (int i = 1; i < s.size(); i++){
while(j >= 0 && s[j + 1] != s[i]){
j = next[j];
}
if (s[j + 1] == s[i]){
j++;
}
next[i] = j;
}
}
bool repeatedSubstringPattern(string s) {
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;
}
};
另外,移动匹配法:
class Solution {
public:
bool repeatedSubstringPattern(string s) {
string t = s + s;
t.erase(t.begin());
t.erase(t.end() - 1);
if (t.find(s) != string::npos) return true;
return false;
}
};
其中,string::npos参数 —— npos 是一个常数,用来表示不存在的位置
if (t.find(s) != string::npos)
如果字符串不存在包含关系,那么返回值就一定是npos
第二次学习KMP算法,感觉理解快了很多,写法也掌握地熟练了。
第九天打卡,加油!!!