-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.permutation.js
More file actions
57 lines (47 loc) · 1.25 KB
/
string.permutation.js
File metadata and controls
57 lines (47 loc) · 1.25 KB
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
/*
* @title: Permutations of String
* @description: Simple function to check for permutations
* @author: Thorsten Kober
* @email: [email protected]
*/
// two words, same length
function permutationOfOther(a, b) {
if (a.length !== b.length) return false;
const letters = {};
let i;
for (i = 0; i < a.length; i++) {
if (letters[a[i]]) letters[a[i]] += 1;
else letters[a[i]] = 1;
}
for (i = 0; i < b.length; i++) {
if (!letters[b[i]]) return false;
letters[b[i]] -= 1;
if (letters[b[i]] < 0) {
return false;
}
}
return true;
}
// permutation of palindrome
function permutationOfPalindrome(a) {
let count = 0;
const found = {};
for (let i = 0; i < a.length; i++) {
if (found[a[i]]) found[a[i]] += 1;
else found[a[i]] = 1;
if (found[a[i]] % 2 === 0) {
count--;
} else {
count++;
}
}
return count <= 1;
}
console.log(permutationOfPalindrome('ottoffsg'));
// npx jest algorithms/string/string.permutation.js
test('test permutations', () => {
expect(permutationOfOther('abcd', 'bcad')).toBe(true);
expect(permutationOfOther('abcd', 'bcaf')).toBe(false);
expect(permutationOfPalindrome('ottoffsg')).toBe(false);
expect(permutationOfPalindrome('oott')).toBe(true);
});