Javascript solution for the wordbreak-ii problem


  • 0
    S

    I have used javascript and tried the solution.

    It seems to always error out for the input s="a", wordDict = ["a"];
    but when i try to console.log( wordDict ) it always gives output as '{}'

    My guess is that there could be validation error for this input.

    var permutation = function(s, dict, words, st, final){
        if(st === s.length){
            return false;
        }
      var word =  '';
      for(var i = st; i < s.length; i++){
        word += s[i];
        if(dict[word]){
          words.push( word );
          if(!permutation(s, dict, words, i + 1, final)){
              
          }
           var sent = '';
           for(var j = 0;j < words.length; j++){
              sent += words[j] + ' ';
           }
          final.push( sent );
          words = [];
        }
      }
      return final;
    };
     
    var wordBreak = function(s, wordDict) {
        var w = [],
            final = [];
        //console.log( wordDict );
        var res = permutation(s , wordDict, w, 0, final);
        return res;
    };

  • 0
    V

    I have a similar issue when running my code. It works fine for the test case they supply and if I run it using the arguments s="a" and wordDict=["a"], but upon submission of the code, I receive the same error. It seems that the an empty object is being passed in for the second argument.

    /**
     * @param {string} s
     * @param {set<string>} wordDict
     * @return {string[]}
     */
    var wordBreak = function(s, wordDict) {
      var results = [];
    
      var findCombos = function(current, pullFrom){
        if (pullFrom.length === 0){
          results.push(current.join(' '));
          return;
        }
    
        for (var i = 0; i < wordDict.length; i++){
          if (pullFrom.indexOf(wordDict[i]) === 0){
            current.push(wordDict[i]);
            findCombos(current, pullFrom.slice(wordDict[i].length));
            current.pop();
          }
        }
      }
      findCombos([], s);
      return results;
    };
    
    wordBreak('catsanddog', ["cat", "cats", "and", "sand", "dog"]);

  • 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.