您的位置:首页 > 其它

[LeetCode] Palindrome Permutation

2015-08-21 17:41 169 查看
Problem Description:

Given a string, determine if a permutation of the string could form a palindrome.

For example,
"code"
-> False,
"aab"
-> True,
"carerac"
-> True.

Hint:

Consider the palindromes of odd vs even length. What difference do you notice?

Count the frequency of each character.

If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?

Just check there are no more than 2 characters that appear an odd number of times in the string.

My C++ code using an array as a hash map is as follows.

class Solution {
public:
bool canPermutePalindrome(string s) {
int odd = 0, counts[256] = {0};
for (char c : s)
odd += ++counts[c] & 1 ? 1 : -1;
return odd <= 1;
}
};


BTW, Stefan has posted many nice solutions here, including the following one that uses bitset.

class Solution {
public:
bool canPermutePalindrome(string s) {
bitset<256> b;
for (char c : s) b.flip(c);
return b.count() < 2;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: