# [LeetCode] 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.)


class Solution {
public:
bool repeatedSubstringPattern(string str) {
int n = str.size();
for (int i = n / 2; i >= 1; --i) {
if (n % i == 0) {
int c = n / i;
string t = "";
for (int j = 0; j < c; ++j) {
t += str.substr(0, i);
}
if (t == str) return true;
}
}
return false;
}
};

class Solution {
public:
bool repeatedSubstringPattern(string str) {
int i = 1, j = 0, n = str.size();
vector<int> dp(n + 1, 0);
while (i < n) {
if (str[i] == str[j]) dp[++i] = ++j;
else if (j == 0) ++i;
else j = dp[j];
}
return dp[n] && (dp[n] % (n - dp[n]) == 0);
}
};

Implement strStr()

Repeated String Match

https://discuss.leetcode.com/topic/68498/one-line-with-regex/2

https://discuss.leetcode.com/topic/67992/java-simple-solution-with-explanation

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2016-11-21 22:37  Grandyang  阅读(16508)  评论(9编辑  收藏  举报