TLE JavaScript, Don't know why


  • 1
    I
    var findSubstring = function(s, words) {
    
    var keyMap = {},
    	arrLen = words.length,
    	sLen = s.length,
    	wordLen = words[0].length, //All word in words has the same length;
    	totalLen = wordLen * arrLen,
    	result = [],
    	index;
    	
    if (sLen < totalLen) {
    	return result;
    }
    	
    //Create hashmap using object in javascript
    for (index = 0; index < arrLen; index++) {
    	keyMap[words[index]] = keyMap.hasOwnProperty(words[index])? keyMap[words[index]] + 1 : 1;
    }
    
    outerloop:
    for (index = 0, boundary = sLen - totalLen; index < boundary; index++) {
    	
    	var resultMap = {}, key, isEqual = true;
    	
    	for (var n = 0; n < arrLen; n++) {
    		key = s.substring(index + wordLen * n, index + wordLen * n + wordLen);
    		if (keyMap.hasOwnProperty(key)) {
    			resultMap[key] = resultMap.hasOwnProperty(key)? resultMap[key] + 1 : 1;
    		} else {
    			continue outerloop;
    		}
    	}
    	
    	//Compare two maps, if the same save the index as one of the anwser. Since keyMap has every property in resultMap, only need to loop keyMap;
    	for (var inst in keyMap) {
    		if (keyMap[inst] !== resultMap[inst]) {
    			isEqual = false;
    			continue outerloop;
    		}
    	}
    	
    	if (isEqual) {
    		result.push(index);
    		index += totalLen - 1;
    	}
    }
    
    return result;
    
    };

Log in to reply
 

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