1. 程式人生 > >Repeated Substring Pattern

Repeated Substring Pattern

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.) 給定一個沒有空格的的字串,檢視該字串是否由其中的一個子串重複多次得到。給定的字串中只有小寫的英文字母,而且長度不超過10000.

例子 1: 輸入: "abab" 輸出: True 解釋:這是由子串"ab"重複得到

例子 2: 輸入: "aba" 輸出: False

例子3 3: 輸入: "abcabcabcabc" 輸出: True 解釋:這是由子串"abc"重複四次得到的,也可以認為是"abcabc重複兩次得到的"

Solution:

1. 暴力法:首先通過所給字串長度枚舉出可以作為重複子串的字串長度,在每個列舉中,分別判斷是否滿足題意。

bool repeatedSubstringPattern(string str) {         int len = str.size();         for (int i = 1; i <= len / 2; i++) {             if (len % i == 0) {                 string sub = str.substr(0, i);                                  int j;                 for (j = 1; j < len / i; j++) {                     if (sub != str.substr(i * j, i)) {                         break;                     }                 }                                  if (j == len / i)                     return true;             }         }                  return false;     }

2. 簡便運算:將兩個所給字串s1首尾相連組成新的字串s2 = s1 + s1,將s2首位字元去掉變為字串s3。

若s1為滿足題意的字串,s3中必存在s1。

class Solution { public:     bool repeatedSubstringPattern(string str) {         int len = str.size();         string newStr = str + str;         newStr = newStr.substr(1, 2 * len - 2);                  return newStr.find(str) != -1;     } };

3,基於KMP思想做的,時間複雜性比較好

bool repeatedSubstringPattern(string str)      {     int i = 1, j = 0, n = str.size();      vector<int> dp(n+1,0);      while( i < str.size() )     { if( str[i] == str[j] )          dp[++i]=++j;      else if( j == 0 ) i++;      else j = dp[j]; }      return dp[n]&&dp[n]%(n-dp[n])==0;      }     }