程序员面试金典 1.4

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)));
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值