blob: 4e2d8d84139cf178ecb6394081388202a6efad95 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
// 459. Repeated Substring Pattern
#include "leetcode.h"
/*
* given a string 's', check if it can be constructed by taking a substring of
* it and appending multiple copies of the substring together.
*/
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int i = 1, j = 0, n = s.size();
vector<int> dp(n + 1, 0);
while (i < n) {
if (s[i] == s[j])
dp[++i] = ++j;
else if (!j)
i++;
else
j = dp[j];
}
return dp[n] && dp[n] % (n - dp[n]) == 0;
}
};
int main() {
Solution obj;
printf("%d\n", obj.repeatedSubstringPattern("abab")); // expect: 1
printf("%d\n", obj.repeatedSubstringPattern("aba")); // expect: 0
printf("%d\n", obj.repeatedSubstringPattern("abcabcabcabc")); // expect: 1
}
|