版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85061459
Title:Repeated Substring Pattern 459
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/repeated-substring-pattern/
1. 将字符串首尾相加,然后将新的字符串的第一位和最后一位去掉,判断原始的字符串是不是新的字符串的子串
时间复杂度:O(1),没有循环语句,但是调用了split方法。
空间复杂度:O(1),没有申请额外空间。
/**
* 将字符串首尾相加,然后将新的字符串的第一位和最后一位去掉,判断原始的字符串是不是新的字符串的子串
* 通过split方法切分,如果切分后的长度为1,则为false,否则为true
* @param s
* @return
*/
public static boolean repeatedSubstringPattern(String s) {
if (s == null || s.length() < 2) {
return false;
}
String newStr = s + s;
newStr = newStr.substring(1, newStr.length() - 1);
System.out.println(newStr);
String str[] = newStr.split(s);
if (str.length == 1) {
return false;
}
else {
return true;
}
}
1. 一个字符串是由某个子字符串组成的,那么这个字符串的长度肯定是这个子字符串长度的倍数,也就是说子字符串长度是这个字符串长度的约数
时间复杂度:O(n^2),嵌套循环,仔细分析也没有n^2。
空间复杂度:O(n),申请额外空间List,其实没有总长度n。
/**
* 一个字符串是由某个子字符串组成的,那么这个字符串的长度肯定是这个子字符串长度的倍数,也就是说子字符串长度是这个字符串长度的约数。
* 某个子字符串肯定是这个字符串的前缀
* @param s
* @return
*/
public static boolean repeatedSubstringPattern1(String s) {
if (s == null || s.length() < 2) {
return false;
}
int len = s.length();
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i < len / 2 + 1; i++) {
if (len % i == 0) {
list.add(i);
}
}
for (int i : list) {
String subStr = s.substring(0, i);
boolean res = true;
for (int j = 0; j < len / i; j++) {
if (!subStr.equals(s.substring(j * i, (j + 1) * i))) {
res = false;
break;
}
else {
continue;
}
}
if (res) {
return true;
}
else {
continue;
}
}
return false;
}