问题描述
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code"
-> False, "aab"
-> True, "carerac"
-> True.
思路分析
回文转置。给一个字符串,判断这个字符串的字符在经过位置变换之后能否形成回文。
要想形成回文,字符必须成对出现,只能有一个非成对的字符(在字符串的中间位置)。所以可以建立一个map,记录每个字符出现的个数,在对出现次数进行处理即可。
代码
class Solution {
public:
bool canPermutePalindrome(string s) {
int map[256] = {0};
for (int i = 0; i < s.length(); i++){
map[s[i]]++;
}
int count = 0;
for (int i = 0; i < 256; i++){
if (map[i] % 2 == 1)
count++;
if (count > 1)
return false;
}
return true;
}
};
时间复杂度:
O(n)
空间复杂度:
O(n)
//n为字符串长度
反思
本来想用一个unordered_map,但是实在是不熟悉,用了这个类似hash的结构。
还可以使用一个bitset,最多只能有一个位置是1,其余都是0。
class Solution {
public:
bool canPermutePalindrome(string s) {
bitset<26> map;
for (auto ch:s){
map[ch - 'a'].flip();
}
return map.count() <= 1;
}
};
这里使用了auto关键字,来自动分配变量。