JavaScript anagram comparison

前端 未结 16 2140
走了就别回头了
走了就别回头了 2020-12-17 02:30

I\'m trying to compare two strings to see if they are anagrams.

My problem is that I\'m only comparing the first letter in each string. For example, \"Mary\" and \"

16条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 02:56

    A more modern solution without sorting.

    function(s, t) {
     if(s === t) return true
     if(s.length !== t.length) return false
    
     let count = {}
    
     for(let letter of s)
      count[letter] = (count[letter] || 0) + 1
    
     for(let letter of t) { 
      if(!count[letter]) return false
      else --count[letter]
     }
    
     return true;
    }
    

提交回复
热议问题