您的位置:首页 > 其它

LeetCode266. Palindrome Permutation

2017-01-05 07:36 393 查看
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;
}
};


4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hashtable