题目:
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" ->
True, "carerac" -> True.
思路:
简单统计每一个字符的出现次数,如果出现奇数次的字符不超过1个,就说明可以构成回文串,否则就无法构成回文串。
代码:
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_map<char, int> hash;
for(int i = 0; i < s.length(); ++i) {
++hash[s[i]];
}
int odd_num = 0;
for(auto it = hash.begin(); it != hash.end(); ++it) {
if(it->second % 2 != 0) {
++odd_num;
}
}
return odd_num <= 1;
}
};
本文介绍了一种简单的算法来判断一个给定的字符串是否可以通过重新排列其字符形成回文串。核心思路在于统计每个字符出现的次数,若出现奇数次的字符不超过一个,则该字符串可以构成回文串。
8万+

被折叠的 条评论
为什么被折叠?



