my-leetcode-logs-20230602

Last updated on 2023年6月7日 晚上

459.重复的子字符串(需要不定时回顾,使用了KMP算法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
//得到前缀表的函数
void getNext(int[] next, String s){
next[0] = 0;
int j = 0;
for(int i = 1;i < s.length();i++){
while(j > 0 && s.charAt(i) != s.charAt(j)){
j = next[j - 1];
}
//判断字符串s中对应位置为i和j是否包含相等的字符
if(s.charAt(i) == s.charAt(j)){
j++;
}
next[i] = j;
}
}

public boolean repeatedSubstringPattern(String s) {
//使用KMP字符串匹配算法实现
if(s.length() == 0){
return false;
}
//构造长度为s.length()的next数组
int[] next = new int[s.length()];
getNext(next, s);
int len = s.length();
if(next[len - 1] != 0 && len % (len - next[len - 1]) == 0){
return true;
}
return false;
}
}

my-leetcode-logs-20230602
https://thewangyang.github.io/2023/06/02/leetcode-notes-20230602/
Author
wyy
Posted on
2023年6月2日
Updated on
2023年6月7日
Licensed under