leetcode 459. Repeated Substring Pattern 暴力拆分即可

小鱼儿 2022-06-03 01:36 189阅读 0赞

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. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <cmath>
  14. using namespace std;
  15. class Solution
  16. {
  17. public:
  18. bool repeatedSubstringPattern(string s)
  19. {
  20. for (int i = s.length() / 2; i >= 1; i--)
  21. {
  22. if (s.length() % i == 0)
  23. {
  24. int c = s.length() / i;
  25. string tmp = "";
  26. for (int j = 0; j < c; j++)
  27. tmp += s.substr(0, i);
  28. if (tmp == s)
  29. return true;
  30. }
  31. }
  32. return false;
  33. }
  34. };

发表评论

表情:
评论列表 (有 0 条评论,189人围观)

还没有评论,来说两句吧...

相关阅读