LeetCode 459: Repeated Substring Pattern (c++)

1699 ワード

一:テーマ
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:愚かな方法、時間の複雑さO(n 2)、前の1,2,...,s.length()/2-1を切り取って、長さ、つなぎ合わせた文字列がソース文字列と同じかどうかを確認します
考え方2:KMPアルゴリズム、時間複雑度O(n)詳しくはブログを参考にKMPを最初から最後まで徹底的に理解できる
三:コード実装
方法1:
class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        
        //    ,          ,                      
        int i=0;
        int j;
        string substring;
        string multipleString;
        
        for(i=0;i

方法2(詳細はブログクリックでリンクを開く)
class Solution {
public:
    bool repeatedSubstringPattern(string s) {
   
        //KMP  
        int len = s.length();
        int next[len+1];
        next[0] = -1;
        int j = 0, k = -1;
        
        while( j