-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhasPalindromePermutation.js
67 lines (38 loc) · 1.35 KB
/
hasPalindromePermutation.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Write an efficient function that checks whether any permutation ↴ of an input string is a palindrome. ↴
// You can assume the input string only contains lowercase letters.
// Examples:
// "civic" should return true
// "ivicc" should return true
// "civil" should return false
// "livci" should return false
function hasPalindromePermutation(theString) {
let set = new Set();
for (let i = 0; i < theString.length; i++) {
if (set.has(theString[i])) {
set.delete(theString[i]);
} else {
set.add(theString[i]);
}
}
return set.size <= 1;
}
// Tests
let desc = 'permutation with odd number of chars';
assertEqual(hasPalindromePermutation('aabcbcd'), true, desc);
desc = 'permutation with even number of chars';
assertEqual(hasPalindromePermutation('aabccbdd'), true, desc);
desc = 'no permutation with odd number of chars';
assertEqual(hasPalindromePermutation('aabcd'), false, desc);
desc = 'no permutation with even number of chars';
assertEqual(hasPalindromePermutation('aabbcd'), false, desc);
desc = 'empty string';
assertEqual(hasPalindromePermutation(''), true, desc);
desc = 'one character string ';
assertEqual(hasPalindromePermutation('a'), true, desc);
function assertEqual(a, b, desc) {
if (a === b) {
console.log(`${desc} ... PASS`);
} else {
console.log(`${desc} ... FAIL: ${a} != ${b}`);
}
}