Code & Func
2018-01-22

第91天。

今天的题目是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: 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.)

一开始没看清,以为只有重复一次的情况,后来发现还可以重复多次,这样的话就不得不多扫描几遍了,有点希尔排序的解法:

1
bool repeatedSubstringPattern1(string s) {
2
for(int i = 1;i < s.size();i++)
3
if (repeatedSubstringPattern(s,i)) return true;
4
return false;
5
}
6
bool repeatedSubstringPattern(string &s,int p) {
7
// cout << p << endl;
8
int size = s.size();
9
if (size % p) return false;
10
for(int i = 0;i < p;i++) {
11
for(int j = i+p;j < size;j += p) {
12
//cout << s[i] << " " << s[j] << endl;
13
if (s[i] != s[j]) return false;
14
}
15
}
2 collapsed lines
16
return true;
17
}

然后是在dicuss中的利用kmp的解法,但我还是没看懂为什么可以这样做。

1
bool repeatedSubstringPattern(string str) {
2
int i = 1, j = 0, n = str.size();
3
vector<int> dp(n+1,0);
4
while( i < str.size() ){
5
if( str[i] == str[j] ) dp[++i]=++j;
6
else if( j == 0 ) i++;
7
else j = dp[j];
8
}
9
return dp[n]&&dp[n]%(n-dp[n])==0;
10
}
上一条动态