Why is there a Time Limit exceeded error with the JS code?


  • 0
    Y

    Hi there, I tried to solve this problem without using any built in functions like "indexOf" or "subString", and wrote the following code. However, there is a wrong time error. Can anyone help me with the code? Why is there an error? How can I correct it?

    var strStr = function(haystack, needle){
    if( typeof(haystack)!== 'string' || typeof(needle) !== 'string'){
    return -1;
    }
    if(needle === ""){
    return 0;
    }
    // abcdef
    // cde
    var haystackLen = haystack.length;

    for (var i = 0; i < haystackLen; i++){
        if (haystack[i] === needle[0]){
            for (var j = 1; j < needle.length; j++){
                if (needle[j] !== haystack[i+j]){
                    break;
                }
            }
            if (j === needle.length){
                return i;
            }
        }
    }
    
    return -1;
    

    };italicised text


  • 0
    Y

    I found out how to pass the OJ!
    I should change the line from for (var j = 1; j < needle.length; j++) to for (var j = 1; j = haystackLen - needle.length + 1; j++}
    This means that I should stop comparing the two strings when the number of characters after j is less than the length of the needle~!


Log in to reply
 

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