CC189 - 1.4

1.4 Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.

Highlight:
How to better interpret a permutation of a palindrome?
The word has an even number of almost all characters.  At most one character in the middle can have a odd count.
-> even string length: all even counts
-> odd string length: at most one odd count

解法一:two iterations

bool isPalindromePurmutation(string str){
    unordered_map<char, int> m;
    for(char c: str){
        m[c]++;
    }
    bool hasOdd = str.size()%2;
    for(auto it=m.begin(); it!=m.end(); it++){
        int count = it->second;
        if(count%2!=0){
            if(hasOdd) {
                hasOdd=0;
            }else{
                return false;
            }
        }
    }
    return true;
}

https://onlinegdb.com/rJyPYVaiV

解法二:one iteration - checking along the iteration

bool isPalindromePurmutation(string str){
    unordered_map<char, int> m;
    int countOdd = 0;
    for(char c: str){
        m[c]++;
        if(m[c]%2==1){
            countOdd++;
        }else{
            countOdd--;
        }
    }
    return countOdd<=1;
}

https://onlinegdb.com/SkL3hETi4

解法三:use a bit vector

There is an elegant way to check if only one bit turns to 1:
00010000 - 1 = 00001111
00010000 & 00001111 = 0

bool isPalindromePurmutation(string str){
    int bit = 0;
    for(char c: str){
        int pos = c-'a';
        bit ^= 1<<pos;
    }
    if(((bit-1)&bit)==0){
        return true;
    }
    return false;
}

https://onlinegdb.com/B1R8kLTjV

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值