Repeated Substring Pattern,repeatedsubstring
分享于 点击 11854 次 点评:284
Repeated Substring Pattern,repeatedsubstring
题目地址:https://leetcode.com/problems/repeated-substring-pattern/
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.
Example 2:
Input: "aba"
Output: False
Example 3:
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
这个问题是要看整个字符串是不是由某个字符串组成的(字符串本身不算)。
如果一个字符串是由某个子字符串组成的,那么这个字符串的长度肯定是这个子字符串长度的倍数,也就是说子字符串长度是这个字符串长度的约数。
那好,有了以上的判断,那就是说如果一个字符串存在所谓的重复字符串模式(Repeated Substring Pattern,简称RSP)的话,那么RSP的可能长度的数目与这个字符串约数的数目是相同的。
而且还有一个特点:RSP肯定是这个字符串的前缀。
有了这些推断,代码就好写多了。
代码实现:
public class RepeatedSubstringPattern {
public boolean repeatedSubstringPattern(String str) {
int len = str.length();
List<Integer> dividerList = new ArrayList<Integer>();
for (int i = 1; i < len; i++) {
if (len % i == 0)
dividerList.add(i);
}
for (int i : dividerList) {
String subStr = str.substring(0, i);
boolean allEqual = true;
for (int k = 0; k < len / i; k++) {
// If there is any unequal, then this substring is not the repeat pattern, try next substring.
// If there are all equal, then this substring is the repeat pattern.
if (!subStr.equals(str.substring(k * i, (k + 1) * i))) {
allEqual = false;
break;
} else {
continue;
}
}
if (allEqual) {
System.out.println(subStr);
return true;
}
else
continue;
}
return false;
}
public static void main(String[] args) {
RepeatedSubstringPattern repeatedSubstringPattern = new RepeatedSubstringPattern();
System.out.println(repeatedSubstringPattern.repeatedSubstringPattern("abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij"));
}
}
相关文章
- 暂无相关文章
用户点评