0%

面试题 01.04. 回文排列

面试题 01.04. 回文排列

##### hashmap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_map<char, int> memo;
for(auto& ch : s)
++memo[ch];
bool isD = false;
for(auto it : memo)
if(it.second & 1)
if(isD)
return false;
else
isD = true;
return true;
}
};

另一种思路,用count计算奇数个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_map<char, int> memo;
int count = 0;
for(auto& ch : s)
{
if(++memo[ch] & 1)
++count;
else
--count;
}
return count <= 1;
}
};

还可以用2个64位长度的long来作为数组来记录。

set
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_set<char> set;
for(auto& ch : s)
if(!set.emplace(ch).second)
set.erase(ch);
return set.size() <= 1;
}
};
计数