Repeated Substring Pattern
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Example 1:
Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.
Example 2:
Input: s = "aba"
Output: false
Example 3:
Input: s = "abcabcabcabc"
Output: true
Explanation: It is the substring "abc" four times or the substring "abcabc" twice.
Constraints:
1 <= s.length <= 104
s consists of lowercase English letters.
思路一:长度为 n 的字符串,获取字符串的子字符串,长度从[1, n/2],然后从这个子字符串构造完整的字符串,最后判断两者是否匹配。
public boolean repeatedSubstringPattern(String s) {
for (int i = 1; i <= s.length() / 2; i++) {
String subStr = s.substring(0, i);
if (repeatedStringMatch(subStr, s)) {
return true;
}
}
return false;
}
public static boolean repeatedStringMatch(String subStr, String s) {
int subLength = subStr.length();
int strLength = s.length();
if (strLength % subLength != 0) {
return false;
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= strLength / subLength; i++) {
sb.append(subStr);
}
return sb.toString().equals(s);
}
思路二:看了官方题解,发现有一种更巧妙的解题思路
假设字符串s是由s1+s2组成的,s+s后,str就变成了s1+s2+s1+s2,去掉首尾,破环了首尾的s1和s2,变成了s3+s2+s1+s4,此时str中间就是s2+s1,如果s是循环字串,也就是s1=s2,所以str中间的s2+s1就和原字符串相等。如果s不是循环字串,s1!=s2,那么s1+s2是不等于s2+s1的,也就是str中间不包含s
String str = s + s;
return str.substring(1, str.length() - 1).contains(s);
标签:459,easy,s2,s1,substring,str,字符串,Input,leetcode
From: https://www.cnblogs.com/iyiluo/p/17023453.html