Why my javascript KMP solution reports a TLE problem?


  • 1
    A
        var strStr = function(haystack, needle) {
        if(needle.length === 0 && haystack.length === 0 ) {
          return 0;
        }        
      var i = 0, j = 0;
      while(i < haystack.length && j < needle.length) {
         console.log(i,j);
        if(haystack.charAt(i) === needle.charAt(j)){
            i++;
            j++;
        }else {
            i += i - j + nextIndex(needle, i, j);
          //  console.log(i,'nextIndex',nextIndex(needle, i, j));
            j = 0;
        }
      }
    
    
      if(j === needle.length) return i - j;
      return -1;  
    };
    
    function nextIndex(str, j) {
        var subStr = str.slice(0,j+1);
        var firstIndex = str.charAt(0);
        var n = subStr.indexOf(firstIndex,1);
        if(n < 0) n = 1;
        return n;
    }

Log in to reply
 

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