-
Notifications
You must be signed in to change notification settings - Fork 1
/
anigram.js
32 lines (30 loc) · 1.05 KB
/
anigram.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// ===============================================================
// Given two strings, write a function to determine if the second
// string is an anagram of the first. An anagram is a word, phrase
// or name formed by rearranging the letters of another, such as:
// cinema, formed from iceman.
// ===============================================================
function validAnagram(first, second) {
// Edgecase to test whether or not both strings are of equal length.
if (first.length !== second.length) {
return false;
}
const lookup = {};
for (let i = 0; i < first.length; i++) {
let letter = first[i];
// if letter exists, increment, otherwise set to 1
lookup[letter] ? (lookup[letter] += 1) : (lookup[letter] = 1);
}
for (let i = 0; i < second.length; i++) {
let letter = second[i];
// can't find letter or letter is zero then it's not an anagram
if (!lookup[letter]) {
return false;
} else {
lookup[letter] -= 1;
}
}
return true;
}
validAnagram('rat', 'car');
validAnagram('anagram', 'nagaram');