JavaScript solution 119ms, easy to understand

  • 0

    If the string S is a repeat of it's sub string, then the first/last character of the string should be the first/last character of the sub string. And the length of the string should be at least two times of the sub string. So we look for the last character from (S.length+1)/2 - 1 to 0, suppose it's index is Ei, then S[0:Ei] maybe a sub string if (S.length % S[0:Ei].length == 0). Repeat the sub string (S.length / S[0:Ei].length) times and compare to the original string S, if equal then return true. If not equal then keep search. If Ei not exist then return false.

    var repeatedSubstringPattern = function(s) {
        if (s.length < 2)  return false;
        var slen = s.length;
        var start = ((slen + 1) >> 1) - 1;
        var end_char = s.charAt(slen - 1);
        var str;
        for (var i = start; i >= 0; i--) {
            var pl = i + 1;
            if (s.charAt(i) === end_char && slen % pl === 0)  {  
                if (s.substr(0, pl).repeat(slen/pl) === s)  return true;
        return false;

Log in to reply

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