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
博客围绕判断字符串是否为回文排列展开。指出回文排列中大多数字符数量为偶数,奇数长度字符串最多一个字符数量为奇数。还给出三种解法,包括两次迭代、一次迭代中检查以及使用位向量,并提供了相应代码链接。

535

被折叠的 条评论
为什么被折叠?



