Palindrome Permutation
Input: Tact Coa
Output: True (permutations:"taco cat'; "atco cta'; etc.)bool isPalindromic(string str) {
if (str.length() < 2) return true;
str.erase(remove_if(str.begin(), str.end(), isspace), str.end());
transform(str.begin(), str.end(), str.begin(), ::tolower);
unordered_map <char, int> char_frequency;
for (auto i : str) {
if (!isalpha(i)) continue;
auto &found = char_frequency.find(i);
if (found == char_frequency.end()) {
// not found
char_frequency.insert({ i, 1 });
}
else {
// found
found->second++;
}
}
// count duplicates
if (str.length() % 2 == 0) {
// even
for (auto i : char_frequency) {
if (i.second != 2) {
return false;
}
}
return true;
}
else {
// odd
bool one_odd_flag = false;
for (auto i : char_frequency) {
if (i.second == 1 && !one_odd_flag) {
one_odd_flag = true;
}
else if (i.second != 2 && one_odd_flag) {
return false;
}
}
return one_odd_flag;
}
}
int main() {
cout << boolalpha << isPalindromic("Tact Coa") << endl;
cout << boolalpha << isPalindromic("asijdia") << endl;
cout << boolalpha << isPalindromic("aassdd") << endl;
cout << boolalpha << isPalindromic("asdasde") << endl;
cout << boolalpha << isPalindromic("sdd") << endl;
pause();
}Last updated