Check whether any permutation of string is a palindrome

Given a string, determine whether any permutation of it is a palindrome.

For example, carrace should return true, since it can be rearranged to form racecar, which is a palindrome. daily should return false, since there's no rearrangement that can form a palindrome.

Example:

Input:  str = "carrace"
Output: true

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str = "carrace";

    map<charintmp;
    for (int i = 0i < str.size(); i++)
    {
        mp[str[i]]++;
    }

    int cnt = 0;
    for (auto it = mp.begin(); it != mp.end(); it++)
    {
        if (it->second & 1)
            cnt++;
    }
    if (cnt > 1)
        cout << "false\n";
    else
        cout << "true\n";

    return 0;
}


No comments:

Post a Comment