LeetCode266. Palindrome Permutation

Problem Description:

Given a string, determine if a permutation of the string could form a palindrome.

For example, “code” -> False, “aab” -> True, “carerac” -> True.

思路:
1. 需要提取保存的信息:每个字符出现的频率
2. 用hashtable统计每一个字符出现次数,如果最多只有一个字符出现次数为奇数,其他字符次数为偶数,则permutation可以form a palindrome.

class Solution {
public:
    bool canPermutePalindrome(string s) {
        //方法1:比较复杂
        vector<int> count(256,0);
        for(auto&k:s){
            if(count[k]==0) count[k]=1;
            else count[k]=0;
        }
        int num=0;
        for(int i=0;i<256;i++){
            if(count[i]) num++;
            if(num>1) return false;
        }
        return true;
    }
};  

class Solution {
public:
    bool canPermutePalindrome(string s) {
        //方法2:用bool优化,同时合并两个for
        vector<bool> count(256,0);
        for(auto&k:s){
            count[k]=!count[k];
            num=num+count[k]?1:-1;
        }
        return num<=1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值