代码随想录第九天|Leetcode28. 找出字符串中第一个匹配项的下标、Leetcode459.重复的子字符串、字符串总结、 双指针回顾
Leetcode28. 找出字符串中第一个匹配项的下标
总的来说用两个指针很简单,暴力解题O(m*n)
class Solution {
public:
int strStr(string A, string B) {
if(A.size()<B.size()) return -1;
for(int i=0;i<=A.size()-B.size();i++){
int j=0;
int temp=i;
while(A[i]==B[j]){
if(j==B.size()-1) return i-B.size()+1;
else{
i++;
j++;
}
}
i=temp;
}
return -1;
}
};
注意
- KMP算法擅长处理的是一长串里找子串
- 其高效之处在于用一个prefix数组保存了子串中头尾衔接点的位置,例如aabaaf,就对应了0 1 0 1 2 0
- prefix数组的使用方法:第j个位置不匹配时,prefix[j-1]就标记了应该退回的位置,就不用暴力从头了。
class Solution {
public:
void getNext(int* next, const string& s) {
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 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 && haystack[i] != needle[j]) {
j = next[j - 1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j == needle.size() ) {
return (i - needle.size() + 1);
}
}
return -1;
}
};
记得二刷
Leetcode459.重复的子字符串
这题只想到了暴力法,O(n^2)遍历两遍,没啥说的。
答案非常nb,根据题目描述,“是否能被多遍子串组成”,这就证明有类似循环节的存在,那么,我们把两个总串s头尾相接,再去掉首元素和尾元素,中间能找到s,就证明了循环节的存在。
一行解决战斗,脑 筋 急 转 弯
class Solution {
public:
bool repeatedSubstringPattern(string s) {
return (s + s).find(s, 1) != s.size();
}
};
find函数使用格式为str.find(s,start,end);
查询范围为[start,end)