Anagrams finder in javascript

2020-05-20 07:10发布

I am supposed to write a program in JavaScript to find all the anagrams within a series of words provided. e.g.: "monk, konm, nkom, bbc, cbb, dell, ledl, llde" The output should be categorised into rows: 1. monk konm, nkom; 2. bbc cbb; 3. dell ledl, llde;

I already sorted them into alphabetical order i.e.: "kmno kmno bbc bbc dell dell" and put them into an array.

However I am stuck in comparing and finding the matching anagram within the array.

Any help will be greatly appreciated.

20条回答
在下西门庆
2楼-- · 2020-05-20 08:04

Javascript objects are excellent for this purpose, since they are essentially key/value stores:

// Words to match
var words = ["dell", "ledl", "abc", "cba"];

// The output object
var anagrams = {};

for (var i in words) {
    var word = words[i];

    // sort the word like you've already described
    var sorted = sortWord(word);

    // If the key already exists, we just push
    // the new word on the the array
    if (anagrams[sorted] != null) {
        anagrams[sorted].push(word);
    } 
    // Otherwise we create an array with the word
    // and insert it into the object
    else {
        anagrams[sorted] = [ word ];
    }
}

// Output result
for (var sorted in anagrams) {
    var words = anagrams[sorted];
    var sep = ",";
    var out = "";
    for (var n in words) {
        out += sep + words[n];
        sep = "";
    }
    document.writeln(sorted + ": " + out + "<br />");
}
查看更多
Lonely孤独者°
3楼-- · 2020-05-20 08:05
  1. Compare string length, if not equal, return false
  2. Create character Hashmap which stores count of character in strA e.g. Hello --> {H: 1, e: 1, l: 2, o: 1}
  3. Loop over the second string and lookup the current character in Hashmap. If not exist, return false, else set value to -1
  4. If none of the above return falsy, it must be an anagram

Time complexity: O(n)

function isAnagram(strA: string, strB: string): boolean {
  const strALength = strA.length;
  const strBLength = strB.length;
  const charMap = new Map<string, number>();

  if (strALength !== strBLength) {
    return false;
  }

  for (let i = 0; i < strALength; i += 1) {
    const current = strA[i];

    charMap.set(current, (charMap.get(current) || 0) + 1);
  }

  for (let i = 0; i < strBLength; i += 1) {
    const current = strB[i];

    if (!charMap.get(current)) {
      return false;
    }

    charMap.set(current, -1);
  }

  return true;
}
查看更多
登录 后发表回答