repeated substring
Topic description: Given a non-empty string, determine whether it can consist of one of its substrings repeated multiple times. The given string contains only lowercase English letters and the length does not exceed 10000.
For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/repeated-substring-pattern/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: String Traversal
First, judging the special case, when the string has only one character, it is impossible to repeat the substring, so return false directly;
Otherwise, traverse the length of the substring from 1 to half the length of the original string, and then loop to judge:
- If the length of the current substring cannot be modulo divided by the length of the original string, the result is 0, indicating that the substring cannot be repeatedly constructed into the original string and skipped directly;
- Get the current substring to be judged;
- According to the length of the original string, how many times the current substring needs to be repeated to form the original string;
- Traverse to determine whether the original string can be formed repeatedly, if so, return true directly, otherwise, continue to judge the next substring.
Finally, if no substring can be repeated multiple times to form the original string, return false.
public class LeetCode_459 {
public static boolean repeatedSubstringPattern(String s) {
// 特殊情况,当该字符串只有一个字符时,不可能由子串重复构成,所以直接返回false
if (s.length() == 1) {
return false;
}
// 记录原字符串的长度
int len = s.length();
// 分别遍历子串的长度从1~原字符串长度的一半
for (int i = 1; i <= len / 2; i++) {
// 如果当前子串的长度不能被原字符串的长度模除结果为0,说明这个子串不可能多次重复构造成原字符串,直接跳过
if (len % i != 0) {
continue;
}
// 获取当前要判断的子串
String repeatSubStr = s.substring(0, i);
boolean allRepeat = true;
// 当前子串需要重复多少次才能构成原字符串
int count = len / i;
// 遍历判断是否可以重复构成原字符串
for (int j = 1; j < count; j++) {
if (!s.substring(j * i, (j + 1) * i).equals(repeatSubStr)) {
allRepeat = false;
break;
}
}
if (allRepeat) {
return true;
}
}
return false;
}
public static void main(String[] args) {
// 测试用例,期望输出: true
System.out.println(repeatedSubstringPattern("abab"));
}
}
[Daily Message] Frustration is a stone. For the weak, it is a stumbling block that stops you from moving forward. And for the strong it is a stepping stone that makes you stand taller.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。