LeetCode 459. 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.)

構想:まずsに対してnext配列を求めて、ずっとnext[len]まで求めて、それからnext[len]-1がゼロではないかどうかを見てk(k=len-(next[len]-1))を除去します
コード:
class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int lens = s.length();
        int next[lens+1];
        int i = 0;
        int j = 0;
        next[0] = 0;
        while (i < lens){//i  s   
            if (j == 0 || s[i] == s[j - 1]){//s[i]         
                ++i;                      //s[j]         
                ++j;
                next[i] = j;
            }
            else{
                j = next[j-1];   //      , j   
            }
        }
        return ((next[lens]-1) && ((next[lens]-1) % (lens - (next[lens]-1)) == 0));
    }
};

出力結果:33 ms