1. 程式人生 > >459. Repeated Substring Pattern(python+cpp)

459. Repeated Substring Pattern(python+cpp)

題目:

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::1]中能找到原字串,就返回true,否則返回false。 解釋: 因為如果是重複的模式,那麼再開頭截掉一個重複單元拼接到後面,一定和原字串相等,但是我們無需做裁剪和拼接,直接複製原字串就完成了類似的操作。 python程式碼:

class Solution(object):
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s:
            return False
        ss=s+s
        return ss[1:-1].find(s)!=-1

c++程式碼:

class Solution {
public:
    bool repeatedSubstringPattern(string s)
{ string ss=s+s; string sub=ss.substr(1,ss.size()-2); return sub.find(s)!=string::npos; } };

總結: 注意要去掉ss的第一個字元和最後一個字元,如果不去掉的話,一定能在ss中找到s的。