C++ 29ms solution utilizing KMP


  • 0
    W
    class Solution {
    public:
        bool repeatedSubstringPattern(string s) {
            if(s.empty()) return false;
            int next[s.size()+1];
            int i = 0, j = -1;
            next[0] = -1;
            while (i < s.size()){
                if (j == -1 || s[i] == s[j]){
                    i++;
                    j++;
                    next[i] = j;
                }else{
                    j = next[j];
                }
            }
            return (s.size()%(s.size()-next[s.size()]) == 0) && next[s.size()] != 0;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.