|
| 1 | +// 49. Group Anagrams |
| 2 | + |
| 3 | +// ["eat","tea","tan","ate","nat","bat"] |
| 4 | +// [["bat"],["nat","tan"],["ate","eat","tea"]] |
| 5 | + |
| 6 | +// [""] |
| 7 | +//[[""]] |
| 8 | + |
| 9 | +// ["a"] |
| 10 | +// [["a"]] |
| 11 | + |
| 12 | +const groupAnagrams = (list) => { |
| 13 | + // result, |
| 14 | + // shift -> for i & k=i+1 |
| 15 | + // twice isAnagram just to check |
| 16 | + // if we find one -> splice(index, 1) |
| 17 | + // -> group.push(item) // until the end of the list |
| 18 | + // until [] |
| 19 | + processWords(list, [], []); |
| 20 | +} |
| 21 | + |
| 22 | +const areTheyAnagrams = (word1, word2) => { |
| 23 | + if (undefined === word2) return false; |
| 24 | + |
| 25 | + let char = word1.split(""), map1 = createAnagramMap(char), map2 = createAnagramMap(word2.split("")); |
| 26 | + // {“e” => 1, “a” => 1, “t” => 1} |
| 27 | + for (let i = 0; i < char.length; i++) { |
| 28 | + if (map1.get(char[i]) !== map2.get(char[i])) return false; |
| 29 | + } |
| 30 | + |
| 31 | + return true; |
| 32 | +} |
| 33 | + |
| 34 | +const createAnagramMap = (char) => { |
| 35 | + let map = new Map(); |
| 36 | + |
| 37 | + for (let i = 0; i < char.length; i++) { |
| 38 | + map.set(char[i], (map.has(char[i]) ? (map.get(char[i]) + 1) : 1)) |
| 39 | + } |
| 40 | + |
| 41 | + return map; |
| 42 | +} |
| 43 | + |
| 44 | +const processWords = (list, groupList, group) => { |
| 45 | + if ([] === list) { |
| 46 | + return groupList; |
| 47 | + } |
| 48 | + |
| 49 | + let curr = list.shift(); // ["eat","tea","tan","ate","nat","bat"] -> ["tea","tan","ate","nat","bat"] |
| 50 | + let tmpList = list; |
| 51 | + |
| 52 | + while ([] !== list) { |
| 53 | + let next = list.shift(); |
| 54 | + if (areTheyAnagrams(curr, next)) group.push(next); |
| 55 | + } |
| 56 | + |
| 57 | + // remove from tmpList that are added into the group |
| 58 | + tmpList.filter((item) => { |
| 59 | + return !group.includes(item); |
| 60 | + }) |
| 61 | + |
| 62 | + // process for groupList |
| 63 | + groupList.push(group); |
| 64 | + |
| 65 | + return processWords(tmpList, groupList, group); |
| 66 | +} |
0 commit comments