JavaScript Solution


  • 0
    S
    var findTheDifference = function(s, t) {
      var hashs = {}
      var hasht = {}
      var diff, code_at
      
      for (var i=0; i<t.length;i++) {
        if(s[i] != undefined) {
          code_at = s[i].charCodeAt(0)
          if (hashs[code_at] != undefined) {
            hashs[code_at] += s[i]
          } else {
            hashs[code_at] = s[i]
          }   
        }
        
        code_at = t[i].charCodeAt(0)
        if (hasht[code_at] != undefined) {
          hasht[code_at]+=t[i]
        } else {
          hasht[code_at] = t[i]
        } 
      }
    
    
      for(var i=0;i<255;i++) {
        if (hasht[i] != hashs[i]) {
          diff = hasht[i][0]
          break
        }
      }
    
      return diff
    }
    
    

  • 0
    S

    Another better performance but similar solution:

    var findTheDifference = function(s, t) {
      var hashs = {}
      var hasht = {}
      var diff, tmpKey
      
      for (var i=0; i<t.length;i++) {
        if(s[i] != undefined) {
          tmpKey = s[i]
          if (hashs[tmpKey] != undefined) {
            hashs[tmpKey] += s[i]
          } else {
            hashs[tmpKey] = s[i]
          }   
        }
        
        tmpKey = t[i]
        if (hasht[tmpKey] != undefined) {
          hasht[tmpKey]+=t[i]
        } else {
          hasht[tmpKey] = t[i]
        } 
      }
    
      var keys = Object.keys(hasht) 
      for(var i=0;i<keys.length;i++) {
        var key = keys[i]
        if (hasht[key] != hashs[key]) {
          diff = hasht[key][0]
          break
        }
      }
    
      return diff
    }
    
    

Log in to reply
 

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