LeetCode - 459. Repeated Substring Pattern - O(n)和O(n^2)兩種思路 - KMP - (C++) - 解題報告


題目

題目鏈接
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重復兩次得到的"

代碼

1.O(n^2)解法

class Solution {
public:
    bool repeatedSubstringPattern(string str) {
        int m=str.size();
        for(int p=1;p<m/2+1;p++)
            for(int i=0;i<m-p;i++)
            {
                if(str[i]!=str[i+p]) break;
                if(m%p==0&&i==m-p-1) return true;
            }
         return false;
    }
};

2.O(n)解法

解法鏈接這是其他人post到討論區的解法,基於KMP思想做的,時間復雜性比較好。KMP算法可以參考這個鏈接

class Solution {
public:
    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;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM