代码随想录算法训练营
今日任务
28. 实现 strStr() ,459.重复的子字符串 ,字符串总结 ,双指针回顾
28. 实现 strStr()
class Solution {
public int strStr(String haystack, String needle) {
char[] haych = haystack.toCharArray();
char[] needch = needle.toCharArray();
int j=0;
int count=0;
int start=-1;
for (int i = 0; i < haych.length; i++) {
if(haych[i]==needch[j]){
count++;
j++;
}else{
if(count!=0){
i=i-j;
}
count=0;
j=0;
}
if(count==needle.length()){
start=i-needle.length()+1;
break;
}
}
return start;
}
}
459.重复的子字符串
//理解kmp
//最长公共前后缀与整个字符串之间的关系
class Solution {
public boolean repeatedSubstringPattern(String s) {
boolean flag=false;
if(s.length()==1){
return flag;
}
int[] next=new int[s.length()];
getNext(next,s);
System.out.println(Arrays.toString(next));
//获得最长公共前后缀的长度
int len=s.length();
int max=next[len-1];
System.out.println(len);
if(max!=-1&&(len%(len-(max+1))==0)){
flag=true;
}
return flag;
}
public void getNext(int[] next, String s){
int j = -1;
next[0] = j;
for (int i = 1; i < s.length(); i++){
while(j >= 0 && s.charAt(i) != s.charAt(j+1)){
j=next[j];
}
if(s.charAt(i) == s.charAt(j+1)){
j++;
}
next[i] = j;
}
}
}
字符串总结
https://programmercarl.com/%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%80%BB%E7%BB%93.html
双指针回顾
https://programmercarl.com/%E5%8F%8C%E6%8C%87%E9%92%88%E6%80%BB%E7%BB%93.html