Day09 字符串part02
28. 实现 strStr()(找出字符串的第一个匹配项下标)
我的思路:
KMP,痛苦面具,AC之后甚至不想复盘。。
看的这个印度阿三哥的讲解觉得悟了,然后写的(https://www.bilibili.com/video/BV18k4y1m7Ar/?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=7f3461e12ee61a8d31183ebf01c3dcb1)
class Solution {
public static int[] getNext(String s) {
char[] ch = s.toCharArray();
int[] result = new int[ch.length];
int index = 0;
for (int i = 1; i < ch.length; ) {
if (ch[i] == ch[index]) {
result[i] = index + 1;
i++;
index++;
}
else {
if(index != 0) {
index = result[index - 1];
}
else {
result[i] = 0;
i++;
}
}
}
return result;
}
public int strStr(String haystack, String needle){
char[] ch1 = haystack.toCharArray();
StringBuffer sB = new StringBuffer();
char[] ch2 = needle.toCharArray();
int[] next = getNext(needle);
int len = 0;
for (int i = 0, j = 0; i < ch1.length && j < ch2.length;) {
if(ch1[i] == ch2[j]) {
sB.append(ch1[i]);
if(sB.length() == needle.length()) {
int index = i - needle.length() + 1;
return index;
}
i++;
j++;
}
else {
if(j > 0) {
int temp = next[j-1];
sB.delete(temp, j);
j = next[j-1];
}
else {
i++;
sB.setLength(0);
}
}
}
return -1;
}
}
我的思路:
基本沿用了上题KMP的Next数组,对其进行判断即可(srds我还是没能AC,最后问了GPT才通过
class Solution {
public boolean repeatedSubstringPattern(String s) {
int[] result = getNext(s);
int len = result.length;
int n = result[len - 1];
if(n != 0 && len % (len - n) == 0) {
return true;
}
return false;
}
public int[] getNext(String s) {
char[] ch = s.toCharArray();
int[] result = new int[ch.length];
int index = 0;
for (int i = 1; i < ch.length; ) {
if (ch[i] == ch[index]) {
result[i] = index + 1;
i++;
index++;
}
else {
if(index != 0) {
index = result[index - 1];
}
else {
result[i] = 0;
i++;
}
}
}
return result;
}
}