Skip to content

Commit b8bb778

Browse files
committed
添加0459.重复的子字符串Java版本
1 parent 786137d commit b8bb778

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

problems/0459.重复的子字符串.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,9 +149,38 @@ public:
149149

150150
## 其他语言版本
151151

152-
153152
Java:
154153

154+
```java
155+
class Solution {
156+
public boolean repeatedSubstringPattern(String s) {
157+
if (s.equals("")) return false;
158+
159+
int len = s.length();
160+
// 原串加个空格(哨兵),使下标从1开始,这样j从0开始,也不用初始化了
161+
s = " " + s;
162+
char[] chars = s.toCharArray();
163+
int[] next = new int[len + 1];
164+
165+
// 构造 next 数组过程,j从0开始(空格),i从2开始
166+
for (int i = 2, j = 0; i <= len; i++) {
167+
// 匹配不成功,j回到前一位置 next 数组所对应的值
168+
while (j > 0 && chars[i] != chars[j + 1]) j = next[j];
169+
// 匹配成功,j往后移
170+
if (chars[i] == chars[j + 1]) j++;
171+
// 更新 next 数组的值
172+
next[i] = j;
173+
}
174+
175+
// 最后判断是否是重复的子字符串,这里 next[len] 即代表next数组末尾的值
176+
if (next[len] > 0 && len % (len - next[len]) == 0) {
177+
return true;
178+
}
179+
return false;
180+
}
181+
}
182+
```
183+
155184

156185
Python:
157186

0 commit comments

Comments
 (0)