Skip to content

Commit 1bdbf26

Browse files
committedJul 28, 2020
Palindrome Permutations
1 parent 1503295 commit 1bdbf26

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
 

‎0266_palindromePermutation.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {string} s String to test for palindrome.
3+
* @return {boolean} Can permutate the string to create valid palindrome.
4+
* @summary Palindrome Permutations {@link https://leetcode.com/problems/palindrome-permutation/}
5+
* @description Given input string - can it be permutated to create a palindrome.
6+
* Space O(1) - Hashmap with entries for unique characters, there is a limited number of those.
7+
* Time O(n) - Loop once for s.length to create a map, after that verify it.
8+
*/
9+
const canPermutePalindrome = s => {
10+
const charCount = {};
11+
12+
for (i = 0; i < s.length; i++) {
13+
if (!charCount[s[i]]) charCount[s[i]] = 1;
14+
else charCount[s[i]] = charCount[s[i]] + 1;
15+
}
16+
17+
const isSingleCharAllowed = !!(s.length % 2);
18+
let hasOddChar = false;
19+
20+
return Object.keys(charCount).every(char => {
21+
const count = charCount[char];
22+
if (count % 2) {
23+
if (isSingleCharAllowed && !hasOddChar) {
24+
hasOddChar = true;
25+
return true;
26+
}
27+
return false;
28+
}
29+
30+
return !(count % 2);
31+
});
32+
};

0 commit comments

Comments
 (0)
Please sign in to comment.