2021.1.22 LeetCode 从零单刷个人笔记整理(持续更新)
github:https://github.com/ChopinXBP/LeetCode-Babel
如果s中包含重复的子字符串,那么说明s中至少包含两个子字符串,s+s至少包含4个字串,前后各去掉一位,查找s是否在新构建的字符串中。
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.
给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。
示例 1:
输入: "abab"
输出: True
解释: 可由子字符串 "ab" 重复两次构成。
示例 2:
输入: "aba"
输出: False
示例 3:
输入: "abcabcabcabc"
输出: True
解释: 可由子字符串 "abc" 重复四次构成。 (或者子字符串 "abcabc" 重复两次构成。)
package Problems;
/**
* 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.
* 给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。
*/
public class RepeatedSubstringPattern {
public boolean repeatedSubstringPattern(String s) {
int len = s.length();
for (int i = 1; i <= len >> 1; i++) {
if (len % i == 0) {
String pattern = s.substring(0, i);
boolean match = true;
for (int j = i; j < len; j += i) {
if (!s.substring(j, j + i).equals(pattern)) {
match = false;
break;
}
}
if (match) {
return true;
}
}
}
return false;
}
//如果s中包含重复的子字符串,那么说明s中至少包含两个子字符串,s+s至少包含4个字串,前后各去掉一位,查找s是否在新构建的字符串中。
public boolean repeatedSubstringPattern2(String s) {
String dblStr = s + s;
return dblStr.substring(1, dblStr.length() - 1).contains(s);
}
}
#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#