leetcode 459. Repeated Substring Pattern 重复子串的确定 + 不需要寻找重复出现的子串 + 暴力拼接即可

向右看齐 2022-05-31 01:39 200阅读 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.)

这道题看起来十分麻烦其实十分简单,直接暴力拼接即可

下面是C++的做法,代码如下:

  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 条评论,200人围观)

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

相关阅读