The fastest javascript solution. 116ms


  • 0
    K
    var wordPattern = function(pattern, str) {
      var arr = str.split(' ');
      var result = true;
    
      var buildMap = function(a, b){
        var ob = {};
        for (var i=0; i<arr.length; i++){
           if(ob[a[i]] == undefined){
             ob[a[i]] = b[i];
           } else {
             if(ob[a[i]] !== b[i]){
             return false;
           }
         }
       }
        return true;
      };
    
      if(pattern.length !== arr.length){
        return false;
      } else {
        result = buildMap(pattern, arr) && buildMap(arr, pattern);
      }
      return result;
    };

Log in to reply
 

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