[LeetCode] Repeated Substring Pattern
文章目录
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.)
Time Complexity
O(k * n)
Space Complexity
O(n)
思路
i means the length of the substring
len/i means how many substring in the string
finally check if the substring append len/i times equals the s
代码
public boolean repeatedSubstringPattern(String s) {
if(s == null || s.length() == 0) return false;
int len = s.length();
for(int i = 1; i <= len/2; i++){
if(len % i == 0){
int subStrLen = len/i;
StringBuilder sb = new StringBuilder();
String str = s.substring(0, i);
for(int j = 0; j < subStrLen; j++){
sb.append(str);
}
if(sb.toString().equals(s)) return true;
}
}
return false;
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论