JavaScript anagram comparison

前端 未结 16 2143
走了就别回头了
走了就别回头了 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 03:03

    function anagrams(str1,str2){
    
          //spliting string into array   
          let arr1 = str1.split("");
          let arr2 = str2.split("");
    
          //verifying array lengths
          if(arr1.length !== arr2.length){
              return false;
          }     
    
          //creating objects
          let frqcounter1={};
          let frqcounter2 ={};
    
        //   looping through array elements and keeping count
          for(let val of arr1){
             frqcounter1[val] =(frqcounter1[val] || 0) + 1; 
          }
          for(let val of arr2){
             frqcounter2[val] =(frqcounter2[val] || 0) + 1; 
          }
    
          console.log(frqcounter1);
          console.log(frqcounter2);
    
          //loop for every key in first object
          for(let key in frqcounter1){
              //if second object does not contain same frq count
              if(frqcounter2[key] !== frqcounter1[key]){
                return false;
              }
          }
          return true;
    
        }
    
        anagrams('anagrams','nagramas');
    

提交回复
热议问题