JavaScript: Why the following code runs perfect on my laptop but returns error when submitting to LeetCode?


  • 1
    L

    The code is as following. The error occurs when I tried to initiate the array f. If I add f[0] = [] before the initiation, it's fine. Can anyone tell me why?

    var wordBreak = function(s, wordDict) {

    	var f = [];
    	var i,j;
    	for (i = 0; i<= wordDict.length; i++){
    		f.push([]);
    	}
    	
    	for (j=0; j<=s.length; j++){
    		f[0][j] = false;
    		if (j<=wordDict.length) {
    		    f[j][0] = true;
    		}
    	}
    	
    	f[0][0] = true;
     	for (i=1; i<wordDict.length+1; i++){
    		for (j=1; j<s.length+1; j++){
    			f[i][j] = false;
    			f[i][j] = f[i-1][j] || f[i][j];
    			if (j>=wordDict[i-1].length){
    				var tmpStr = s.slice(0,j);
    				var word = tmpStr.slice(-wordDict[i-1].length);
    				if (word == wordDict[i-1]) {
    					f[i][j] = (f[i][j]) || (f[i-1][j-wordDict[i-1].length] && true);
    					f[i][j] = f[i][j] || f[i][j-wordDict[i-1].length];
    				}
    			}
    		}
    	}
    	var x = wordDict.length;
    	var y = s.length
    	return f[x][y];        
    

    };

    var str = "a";
    var dict = [];

    console.log(wordBreak(str, dict));


  • 0
    W

    test cases are wrong, f**k, you can log out all the input arguments


  • 0

    Despite the name wordDict which implies a dictionary, it is actually a Set object.


Log in to reply
 

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