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