代码随想录算法训练营Day9 | 28. 实现 strStr() 459.重复的子字符串 字符串总结 双指针回顾
28. 实现 strStr()
题目链接:LeetCode 704 二分查找
思路:
1.构建next数组
2.next遍历
class Solution {
public:
vector<int> getNext(string& s){
int j = 0;
vector<int> next(s.size());
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;
}
return next;
}
int strStr(string haystack, string needle) {
if(needle.size()==0) return 0;
vector<int> next = getNext(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;
}
};
注意 :
- 注意next数组下标
LeetCode 459.重复的子字符串
题目链接:LeetCode 704 二分查找
思路:
1.用next数组
2.next数组len-next(len-1)如果能被len整除,说明可以由其生成
class Solution {
public:
vector<int> getNext(string s){
vector<int> next(s.size());
next[0] = 0;
int j = 0;
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;
}
return next;
}
bool repeatedSubstringPattern(string s) {
int j = 0;
vector<int> next = getNext(s);
int len = s.size();
if (next[len-1]!=0 && len%(len-next[len-1])==0) return true;
return false;
}
};
注意 :
- 注意最后一个元素为len-1;
字符串总结
1.双指针法
2.库函数的使用
3.反转系列
4.KMP算法
双指针回顾
1.数组删除只能覆盖
2.数组扩容后向后填充
分为数组、字符串和链表