Longest Palindrome in C++


Suppose we have a string which consists of lowercase or uppercase letters, we have to find the length of the longest palindromes that can be built with those letters. Now the string is case sensitive, so "Aa" is not considered a palindrome here.

So, if the input is like "abccccdd", then the output will be 7, as one longest palindrome that can be built is "dccaccd", whose length is 7.

To solve this, we will follow these steps −

  • Define one map mp

  • for each character i in s

    • (increase mp[i] by 1)

  • ma := 0, c := 0, ans := 0

  • for each key-value pair i in mp

    • if value of imod 2 is same as 1, then −

      • (increase ma by 1)

    • c := c + value of i

  • if ma > 0, then −

    • (decrease ma by 1)

  • ans := c - ma

  • return ans

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int longestPalindrome(string s) {
      unordered_map<char, int> mp;
      for (auto i : s)
         mp[i]++;
      int ma = 0, c = 0, ans = 0;
      for (auto i : mp) {
         if ((i.second) % 2 == 1)
            ma++;
         c += i.second;
      }
      if (ma > 0)
         ma--;
      ans = c - ma;
      return ans;
   }
};
main(){
   Solution ob;
   cout << (ob.longestPalindrome("abccccdd"));
}

Input

"abccccdd"

Output

7

Updated on: 10-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements