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.)
分析
这道题暴力搜索所有重复的可能,s的长度为length,搜索<length,所有可以整除length的数值,然后判断是否是重复的。
看到还有一种更巧妙的解法,如果s为重复的,例如可以分为n个重复的子串,n>=2,那么s1 = s+s肯定也会有2*n的重复的子串,那么将s1的首尾字母去除后,s1仍然包含2*n-2个重复的子串,那么s可以在s1中找到。但是这个解法需要证明不重复的子串s这样操作一定不存在s1中。这个证明的解法还没有想明白。
Code
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int length = s.size();
if (length == 0)
return true;
string s1 = s + s;
s1.pop_back();
s1.erase(0, 1);
if (s1.find(s) == std::string::npos)
return false;
else
return true;
}
};
运行效率
Runtime: 36 ms, faster than 76.88% of C++ online submissions for Repeated Substring Pattern.
Memory Usage: 14.2 MB, less than 88.06% of C++ online submissions forRepeated Substring Pattern.