Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from youngyangyang04:master #527

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 8 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Jan 21, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
添加0459.重复的子字符串.md的Java版本二前缀表不减一
  • Loading branch information
curforever committed Jan 15, 2025
commit 275efa0c70ecdb36c2c77eb2e26059b7b8b29d03
42 changes: 41 additions & 1 deletion problems/0459.重复的子字符串.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,8 @@ public:

### Java:

(版本一) 前缀表 减一

```java
class Solution {
public boolean repeatedSubstringPattern(String s) {
Expand Down Expand Up @@ -420,6 +422,45 @@ class Solution {
}
```

(版本二) 前缀表 不减一

```java
/*
* 充分条件:如果字符串s是由重复子串组成的,那么它的最长相等前后缀不包含的子串一定是s的最小重复子串。
* 必要条件:如果字符串s的最长相等前后缀不包含的子串是s的最小重复子串,那么s必然是由重复子串组成的。
* 推得:当字符串s的长度可以被其最长相等前后缀不包含的子串的长度整除时,不包含的子串就是s的最小重复子串。
*
* 时间复杂度:O(n)
* 空间复杂度:O(n)
*/
class Solution {
public boolean repeatedSubstringPattern(String s) {
// if (s.equals("")) return false;
// 边界判断(可以去掉,因为题目给定范围是1 <= s.length <= 10^4)
int n = s.length();

// Step 1.构建KMP算法的前缀表
int[] next = new int[n]; // 前缀表的值表示 以该位置结尾的字符串的最长相等前后缀的长度
int j = 0;
next[0] = 0;
for (int i = 1; i < n; i++) {
while (j > 0 && s.charAt(i) != s.charAt(j)) // 只要前缀后缀还不一致,就根据前缀表回退j直到起点为止
j = next[j - 1];
if (s.charAt(i) == s.charAt(j))
j++;
next[i] = j;
}

// Step 2.判断重复子字符串
if (next[n - 1] > 0 && n % (n - next[n - 1]) == 0) { // 当字符串s的长度可以被其最长相等前后缀不包含的子串的长度整除时
return true; // 不包含的子串就是s的最小重复子串
} else {
return false;
}
}
}
```

### Python:

(版本一) 前缀表 减一
Expand Down Expand Up @@ -930,4 +971,3 @@ bool repeatedSubstringPattern(char* s) {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

AltStyle によって変換されたページ (->オリジナル) /