[LeetCode]459. Repeated Substring Pattern
题目描述
思路
- 暴力解法
- 动归解法
状态数组第i位表示到当前位置位置重复出现的字符个数
到当前位置重复出现的字符个数不为0,且重复出现的字符个数是总字符串减去重复出现的字符数的整数倍,即满足条件,返回true,否则返回false
代码
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
bool repeatedSubstringPattern(string s) {
/*暴力解法
string repeat = "";
int repeatLen = 1;
while (repeatLen < s.size()) {
repeat = s.substr(0, repeatLen);
int i = repeatLen;
while (i < s.size()) {
if (repeat == s.substr(i, repeatLen))
i += repeatLen;
else
break;
}
if (i == s.size())
return true;
else
++repeatLen;
}
return false;
*/
//动态规划解法
vector<int> dp(s.size() + 1, 0);
int i = 1, j = 0;
while (i < s.size()) {
if (s[i] == s[j])
dp[++i] = ++j;
else if (j == 0)
++i;
else
j = dp[j];
}
return dp[s.size()] && (dp[s.size()] % (s.size() - dp[s.size()])) == 0;
}
};
int main() {
Solution s;
cout << s.repeatedSubstringPattern("bbabba") << endl;
system("pause");
return 0;
}