JavaScript anagram comparison

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

    an anagram with modern javascript that can be use in nodejs. This will take into consideration empty strings, whitespace and case-sensitivity. Basically takes an array or a single string as input. It relies on sorting the input string and then looping over the list of words and doing the same and then comparing the strings to each other. It's very efficient. A more efficient solution may be to create a trie data structure and then traversing each string in the list. looping over the two words to compare strings is slower than using the built-in string equality check.

    The function does not allow the same word as the input to be considered an anagram, as it is not an anagram. ;) useful edge-case.

    const input = 'alerting';
    const list1 = 'triangle';
    const list2 = ['', ' ', 'alerting', 'buster', 'integral', 'relating', 'no', 'fellas', 'triangle', 'chucking'];
    
    const isAnagram = ((input, list) => {
      if (typeof list === 'string') {
        list = [list];
      }
    
      const anagrams = [];
      const sortedInput = sortWord(input).toLowerCase();
      const inputLength = sortedInput.length;
      list.forEach((element, i) => {
        if ( inputLength === element.length && input !== element ) {
          const sortedElement = sortWord(element).toLowerCase();
          if ( sortedInput === sortedElement) {
            anagrams.push(element);
          }
        }
      });
    
      return anagrams;
    })
    
    const sortWord = ((word) => {
      return word.split('').sort().join('');
    });
    
    console.log(`anagrams for ${input} are: ${isAnagram(input, list1)}.`);
    console.log(`anagrams for ${input} are: ${isAnagram(input, list2)}.`);
    
    0 讨论(0)
  • 2020-12-17 02:58

    This considers case sensitivity and removes white spaces AND ignore all non-alphanumeric characters

    function compare(a,b) {
        var c = a.replace(/\W+/g, '').toLowerCase().split("").sort().join("");
        var d = b.replace(/\W+/g, '').toLowerCase().split("").sort().join("");
            return (c ===d) ? "Anagram":"Not anagram";
    }

    0 讨论(0)
  • 2020-12-17 03:00
     //The best code so far that checks, white space, non alphabets 
     //characters 
     //without sorting   
    function anagram(stringOne,stringTwo){
    var newStringOne = ""
    var newStringTwo = ''
    for(var i=0; i<stringTwo.length; i++){
     if(stringTwo[i]!= ' ' && isNaN(stringTwo[i]) == true){
        newStringTwo =  newStringTwo+stringTwo[i]
     }
        }
    
    for(var i=0; i<stringOne.length; i++){
        if(newStringTwo.toLowerCase().includes(stringOne[i].toLowerCase())){
        newStringOne=newStringOne+stringOne[i].toLowerCase()
        }
    }
    console.log(newStringOne.length, newStringTwo.length)
    if(newStringOne.length==newStringTwo.length){
        console.log("Anagram is === to   TRUE")
    }
    else{console.log("Anagram is === to   FALSE")}
    }
    anagram('ddffTTh@@@#$', '@dfT9t@D@#H$F')
    
    0 讨论(0)
  • 2020-12-17 03:02

    Here is a simple algorithm: 1. Remove all unnecessary characters 2. make objects of each character 3. check to see if object length matches and character count matches - then return true

                const stripChar = (str) => 
                {
                   return str.replace(/[\W]/g,'').toLowerCase();
                }
                const charMap = str => {
                     let MAP = {};
                     for (let char of stripChar(str)) {
                         !MAP[char] ? (MAP[char] = 1) : MAP[char]++;
                     }
                  return MAP;
                };
    
          const anagram = (str1, str2) => {
     if(Object.keys(charMap(str1)).length!==Object.keys(charMap(str2)).length) return false;
              for(let char in charMap(str1))
              {
                if(charMap(str1)[char]!==charMap(str2)[char]) return false;
              }
              return true;
            };
    
        console.log(anagram("rail safety","!f%airy tales"));
    
    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2020-12-17 03:05

    No need for sorting, splitting, or joining. I think this is the simplest, most efficient way to go:

    const Anagrams = (str1 = '', str2 = '') => {
        if (typeof str1 !== 'string' || typeof str2 !== 'string') {
            return false;
        }
    
        if (str1.length !== str2.length) {
            return false;
        }
        
        if (str1 === str2) {
            return true;
        }
    
        const charCount = [];
        let startIndex = 0;
    
        for (let i = 0; i < str1.length; i++) {
            const charInt1 = str1.charCodeAt(i);
            const charInt2 = str2.charCodeAt(i);
            
            startIndex = charInt1 <= charInt2 ? charInt1 : charInt2;
            
            charCount[charInt1] = (charCount[charInt1] || 0) + 1;           
            charCount[charInt2] = (charCount[charInt2] || 0) - 1;           
        }
    
        while (charCount.length >= startIndex) { 
            if (charCount.pop()) {
                return false;
            }
        }
    
        return true;
    }
    
    console.log(Anagrams('afc','acf'))//true
    console.log(Anagrams('baaa','bbaa'))//false
    console.log(Anagrams('banana','bananas'))//false
    console.log(Anagrams('',' '))//false
    console.log(Anagrams(9,'hey'))//false
    
    0 讨论(0)
提交回复
热议问题