allAnagrams

Written on September 8, 2019

문제

Given a single input string, write a function that produces all possible anagrams of a string and outputs them as an array. At first, don’t worry about repeated strings. What time complexity is your solution?

Extra credit: Deduplicate your return array without using uniq().

example usage:

var anagrams = allAnagrams("abc");
console.log(anagrams); // [ 'abc', 'acb', 'bac', 'bca', 'cab', 'cba' ]

풀이

var allAnagrams = function(string) {
  let stringObj = {};
  for (let i = 0; i < string.length; i++) {
    stringObj[i] = false;
  }
  let anagramsObj = {};

  const makeAnagrams = (word, obj) => {
    if (word.length === string.length) {
      if (!anagramsObj[word]) {
        anagramsObj[word] = true;
      }
      return;
    }
    for (let i = 0; i < string.length; i++) {
      let newWord = word;
      if (!obj[i]) {
        newWord += string[i];
        obj[i] = !obj[i];
        makeAnagrams(newWord, obj);
        obj[i] = !obj[i];
      }
    }
  };
  makeAnagrams("", stringObj);
  return Object.keys(anagramsObj);
};

👩🏻‍💻 배우는 것을 즐기는 프론트엔드 개발자 입니다
부족한 블로그에 방문해 주셔서 감사합니다 🙇🏻‍♀️

in the process of becoming the best version of myself