JavaScript - CodeKata #18 ๐Ÿ“Œ

devmoonshยท2020๋…„ 9์›” 30์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
43/48
post-thumbnail

1. Question

๋‹ค์Œ๊ณผ ๊ฐ™์ด input์ด ์ฃผ์–ด์กŒ์„ ๋•Œ,๊ฐ™์€ ์•ŒํŒŒ๋ฒณ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋‹จ์–ด๋ผ๋ฆฌ ๋ฌถ์–ด์ฃผ์„ธ์š”.

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

output์—์„œ ์ˆœ์„œ๋Š” ์ƒ๊ด€์—†์Šต๋‹ˆ๋‹ค.


2. Answer

const groupAnagrams = strs => {
  let results = [];
  for (let i = 0; i < strs.length; i++) {
    let temp = [strs[i]];
    for (let j = i+1; j < strs.length; j++) {
      let isTrue = true;
      for (let k = 0; k < strs[j].length; k++) {
        if (!strs[i].includes(strs[j][k])) {
          isTrue = false;
          break;
        }
      }
      if (isTrue) {
        temp.push(strs[j]);
        strs[j] = ''
      }
    }
    let container = []
    while (temp.length) {
      if (temp[0] !== '') {
        container.push(temp.shift());
      } else {
        temp.shift();
      }
    }
    if (container.length) {
      results.push(container)
    }
  }
  return results;
}

console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))

Ref.
https://choiseungyoun.github.io/posts/TIL-Day31:-Code-Kata-18(JS-&-PY)/

profile
Junior front-end developer

0๊ฐœ์˜ ๋Œ“๊ธ€