Word Ladder Javascript wordDict TypeError: undefined is not a function


  • 0
    B

    I'm not sure how to access the wordDict in JS. I have the type error all the time, and when I try to list all the method of the wordDict by using: Object.getOwnPropertyNames(Set), the methods are [ 'length', 'name', 'arguments', 'caller', 'prototype' ]. I thought there should be contains and remove method. Can someone point me how to change my code to make this works? Thanks.

     var Queue = function(){
       this._storage = [];
       this.push = function(value){
         this._storage.push(value);
       };
       this.peek = function(){
         return this._storage[0];
       };
       this.pop = function(){
         return this._storage.shift();
       };
       this.size = function(){
         return this._storage.length;
       };
       this.isEmpty = function(){
         return this._storage.length === 0;
       };
     } ;
    var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
    
    var ladderLength = function(beginWord, endWord, wordDict) {
      console.log("list all the method ", Object.getOwnPropertyNames(Set));
      var queue = new Queue();
      queue.push(beginWord);
      wordDict.discard(beginWord);
      var pathLength = 1;
    
      while(!queue.isEmpty()){
        var count = queue.size();
        for(var i = 0; i < count; i++){
          var current = queue.pop();
          for(var c = 0; c < 26; c++){
            for(var j = 0; j < current.length; j++){
              if(alphabet[c] ===current[j]){
                continue;
              }
              var temp = replace(current, j, alphabet[c]);
              if(temp === end){
                return pathLength + 1;
              }
              if(wordDict.contains(temp)){
                queue.push(temp);
                wordDict.discard(temp);
              }
            }
          }
        }
        pathLength++;
      }
      return 0;
    };
    
    var replace = function(inputString, index, character){
      var alphabetArr = inputString.split('');
      alphabetArr[index] = character;
      return alphabetArr.join('');
    };

  • 0
    C

    These are the methods accessible to you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

    one of obvious things - size is a member var, not a function


Log in to reply
 

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