回家休息了小半个月,荒废了不少,今天继续。
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.)
翻译:
给定一个非空字符串,检查它是否可以通过获取一个子字符串并将子字符串的多个副本附加在一起来构造。您可以假定给定的字符串仅由小写的英文字母组成,其长度不会超过10000。
示例1:
输入: “abab” 输出: True 说明:这是子串“ab”两次。
示例2:
输入: “aba” 输出: False
示例3:
输入: “abcabcabcabc” 输出: True 说明:这是子串“abc”四次。(和子串“abcabc”两次)
public boolean repeatedSubstringPattern(String s) {
int len = s.length();
for(int i=1; i<=len/2 ; i++){
String temp = s;
String subs = temp.substring(0,i);
String rp_temp = temp.replaceAll(subs,"");//替换时subs已经为字符串,要熟悉正则表达式的使用
if(rp_temp.isEmpty()) return true;
}
return false;
}
答案思路:也是先截取部分字符,不同点在于用截取的字符串组成新字符串与原字符对比,这里StringBuilder性能更快。
public boolean repeatedSubstringPattern(String s) {
int len = s.length();
for(int i=1; i<=len/2 ; i++){
if(len%i == 0){//整串字符数为子串的整数倍
int m = len/i;
String subs = s.substring(0,i);
StringBuilder sb = new StringBuilder("");
for(int j = 0;j<m;j++){
sb.append(subs);
}
if(sb.toString().equals(s)) return true;
}
}
return false;
}