leetcode-459-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:

1
2
3
Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.

Example 2:

1
2
Input: "aba"
Output: False

Example 3:

1
2
3
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

分析


解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int size = s.size();

for (int i = size/2; i >= 1; i--) {
if (size%i == 0) {
int count = size / i;
string tmp = "";
for (int j = 0; j < count; j++) {
tmp += s.substr(0, i);
}
if (tmp == s) {
return true;
}
}
}
return false;
}
};

解决方案2(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func repeatedSubstringPattern(s string) bool {
sLength := len(s)
for i := 1; i <= sLength/2; i++ {
if sLength % i != 0 {
continue
}
count := sLength / i
j := 1
for ; j < count; j++ {
if s[i*(j-1): i*j] != s[i*j: i*(j+1)] {
break
}
if j == count-1 {
return true
}
}
}
return false
}

相关问题


题目来源