Palindrome Permutation:判断一个字符串是否可以组成一个回文字符串。
首先要想想回文串有什么特点,至少所有的字符都应该有偶数个,这样才能一边一半,然后最中间的字符可以只出现奇数次,所以可以给出下面的解法:使用一个数组来记录每个字符出现的次数,最后算一下奇数的个数,时间复杂度为O(n)
。
class Solution {
public:
bool canPermutePalindrome(string s) {
int cnt[128] = { 0 };
for(auto c : s)
{
cnt[c]++;
}
bool bOdd = false;
for(int i = 0; i < 128; i++)
{
if(cnt[i] & 0x1 == 1){
if(!bOdd) bOdd = true;
else return false;
}
}
return true;
}
};
稍微优化一下,可以把奇数的判断放在循环里,但是其实没有什么本质区别。
class Solution {
public:
bool canPermutePalindrome(string s) {
int cnt[128] = { 0 }, cOdd = 0;
for(auto c : s)
{
cnt[c]++;
if(cnt[c] & 0x1 == 1) cOdd++;
else cOdd--;
}
return cOdd <= 1;
}
};
仔细想一下是可以优化存储空间的。我们根本不需要记录每个字符的数量,只需要知道字符是奇数个还是偶数个就可以了,比如对一盏灯来回开和关,知道灯的初始状态和结束状态就能知道是执行了奇数次还是偶数次操作。
这样通过位向量就可以优化存储空间了,基本的操作是翻转比特位,最后再判断置位比特位的数量就可以了。
注:下面的原文我懒得翻译了,借用另一道题的解法。为了判断整数n
二进制表示中1
的个数,可以通过n & (n - 1)
消掉n
中最右边的1
,这样就能得到n
的二进制表示中1
的个数了。
class Solution {
public:
bool canPermutePalindrome(string s) {
int iSet = 0;
for(auto c : s)
{
iSet ^= 1 << (tolower(c) - 'a');
}
return !(iSet & (iSet - 1));
}
};
因为leetcode上的测试用例有特殊字符,只能借助bitset
了。
class Solution {
public:
bool canPermutePalindrome(string s) {
bitset<128> bits;
for(auto c : s)
{
bits.flip(c);
}
return bits.count() <= 1;
}
};
但是这个太慢了,才击败57.79%
,所以还是用long long
。
class Solution {
public:
bool canPermutePalindrome(string s) {
long long ll[2] = { 0 };
for(auto c : s)
{
ll[c >> 6] ^= ((long long)1) << (c & 0x3f);
}
//如果两部分都不为0,则直接返回false
//然后如果某一部分1的个数太多,也返回false
return !(ll[0] && ll[1]) && !((ll[0] & (ll[0] - 1)) || (ll[1] & (ll[1] - 1)));
}
};