Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1bdbf26

Browse files
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

Lines changed: 32 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /