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));
    }
};

输出结果: 33ms

你可能感兴趣的:(C/C++,LeetCode,String)