找出字符串中第一个匹配项的下标
其实kmp算法我已经学过两次了,大一的时候培训学过一次,大二的时候数据结构又学过一次,但是还是没有记牢,每次到了写代码的时候都要去翻笔记或者查资料,算上这次是第三次,这次一定多复习把他牢牢地掌握。
class Solution {
public int strStr(String haystack, String needle) {
int[] next = new int[needle.length()];
getNext(next, needle);
int j = 0;
for (int i = 0; i < haystack.length(); i++) {
while (j > 0 && needle.charAt(j) != haystack.charAt(i)) {
j = next[j - 1];
}
if (needle.charAt(j) == haystack.charAt(i)) {
j++;
}
if (j == needle.length()) {
return i - needle.length() + 1;
}
}
return -1;
}
public void getNext(int[] next, String s) {
int j = 0;
next[0] = j;
for (int i = 1; i < s.length(); i++) {
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = next[j - 1];
}
if (s.charAt(j) == s.charAt(i)) {
j++;
}
next[i] = j;
}
}
}
重复的子字符串
看到这题我想起我很久之前做过一道求循环节长度的题,当时我就是用next数组求解的,想着这题能不能也用当时的方法做出来,就写了下面的代码,没想到直接过了。
然后去看了视频讲解发现也是同一种方法,所以就没有改代码。
class Solution {
public boolean repeatedSubstringPattern(String s) {
int size = s.length();
int[] next = new int[size];
getNext(next, s);
if (next[size - 1] == 0) {
return false;
}
int length = s.length() - next[size - 1]; //循环节长度
if(size % length == 0) {
return true;
}
return false;
}
public void getNext(int[] next, String s) {
int j = 0;
next[0] = j;
for (int i = 1; i < s.length(); i++) {
while (j > 0 && s.charAt(j) != s.charAt(i)) {
j = next[j - 1];
}
if (s.charAt(j) == s.charAt(i)) {
j++;
}
next[i] = j;
}
}
}