class Solution:
def canPermutePalindrome(self, s: str) -> bool:
from collections import Counter
count = Counter(s)
odd_count = sum(1 for v in count.values() if v % 2 != 0)
return odd_count <= 1
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_map<char, int> count;
for (char c : s) count[c]++;
int odd = 0;
for (auto &kv : count) {
if (kv.second % 2 != 0) odd++;
}
return odd <= 1;
}
};
class Solution {
public boolean canPermutePalindrome(String s) {
int[] count = new int[128];
for (char c : s.toCharArray()) count[c]++;
int odd = 0;
for (int v : count) {
if (v % 2 != 0) odd++;
}
return odd <= 1;
}
}
var canPermutePalindrome = function(s) {
const count = {};
for (let c of s) {
count[c] = (count[c] || 0) + 1;
}
let odd = 0;
for (let key in count) {
if (count[key] % 2 !== 0) odd++;
}
return odd <= 1;
};
Given a string s
, determine if a permutation of s
could form a palindrome. You do not need to return the actual palindrome, just whether it is possible to rearrange the characters of s
so that the result is a palindrome string.
Constraints:
s
.s
.
The first instinct might be to try generating all possible permutations of s
and check if any of them is a palindrome. However, that would be highly inefficient since the number of permutations grows factorially with the length of the string.
Instead, let's consider what makes a string a palindrome. A palindrome reads the same forwards and backwards. For a string to be rearranged into a palindrome:
s
have odd counts.
Here is how we can solve the problem efficiently:
s
. This allows us to quickly look up and update counts as we iterate through the string.
This approach is efficient because:
n
), where n
is the length of the string.k
) where k
is the number of distinct characters.
Let's walk through an example with s = "aabbcc"
:
Another example: s = "aabbc"
s = "abc"
:
Brute-force approach:
n!
) time, where n
is the length of the string.n!
) for storing permutations.n
) time.k
) time, where k
is the number of unique characters (at most 26 for lowercase English letters).n
).k
) for the hash map or array.To determine if a string can be permuted into a palindrome, we simply count how many characters have odd frequencies. If there is more than one such character, it's impossible; otherwise, it is possible. This insight allows us to solve the problem in linear time and space, making the solution both elegant and efficient.