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