thanhnguyennguyen /
cff
| 1 | |||
| 2 | const preProcess = (str) => { |
||
| 3 | return str.toLowerCase().replace(/[^\w]/g, ""); |
||
| 4 | } |
||
| 5 | |||
| 6 | const buildCharacterMap = (str) => { |
||
| 7 | let characterMap = {}; |
||
| 8 | for (let character of str) { |
||
| 9 | characterMap[character] = ++characterMap[character] || 1; |
||
| 10 | } |
||
| 11 | return characterMap; |
||
| 12 | } |
||
| 13 | |||
| 14 | const anagrams = (strA, strB) => { |
||
| 15 | // put your code here to address problems |
||
| 16 | |||
| 17 | |||
| 18 | // lowercase and remove special character |
||
| 19 | strA = preProcess(strA) |
||
| 20 | strB = preProcess(strB); |
||
| 21 | |||
| 22 | // check length first to avoid wasting time |
||
| 23 | if (strA.length !== strB.length) { |
||
| 24 | return false; |
||
| 25 | } |
||
| 26 | let characterMapA = {}, |
||
| 27 | characterMapB = {}; |
||
|
0 ignored issues
–
show
Unused Code
introduced
by
Loading history...
|
|||
| 28 | // init character map for strA |
||
| 29 | characterMapA = buildCharacterMap(strA); |
||
| 30 | // init character map for strB |
||
| 31 | characterMapB = buildCharacterMap(strB); |
||
| 32 | |||
| 33 | // compare 2 objects |
||
| 34 | for (let char in characterMapA) { |
||
| 35 | if (characterMapA[char] !== characterMapB[char]) { |
||
| 36 | return false; |
||
| 37 | } |
||
| 38 | } |
||
| 39 | return (characterMapA.length === characterMapB.length); |
||
| 40 | } |
||
| 41 | |||
| 42 | const anagrams2 = (strA, strB) => { |
||
| 43 | return (preProcess(strA).split('').sort().join('') === preProcess(strB).split('').sort().join('')) |
||
| 44 | } |
||
| 45 | |||
| 46 | module.exports = {anagrams, anagrams2}; |
||
| 47 |