Longest Palindrome

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

Example:

Input: s = "abccccdd"
Output: 7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

Approach:

C++

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

int longestPalindrome(string s)
{
    map<charint> mp;
    for (int i = 0; i < s.size(); i++)
        mp[s[i]]++;
    int f = 0;
    int ans = 0;
    for (auto it = mp.begin(); it != mp.end(); it++)
    {
        if (it->second & 1)
        {
            ans += it->second - 1;
            f = 1;
        }
        else
            ans += it->second;
    }
    if (f == 1)
        ans += 1;
    return ans;
}

int main()
{

    string s = "abccccdd";

    cout << longestPalindrome(s);

    return 0;
}


No comments:

Post a Comment