Longest Palindrome Problem


Description

LeetCode Problem 409.

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

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

Example 1:

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

Example 2:

1
2
Input: s = "a"
Output: 1

Example 3:

1
2
Input: s = "bb"
Output: 2

Constraints:

  • 1 <= s.length <= 2000
  • s consists of lowercase and/or uppercase Englishletters only.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
    int longestPalindrome(string s) {
        unordered_map<int,int> mp;
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
            mp[s[i]] ++;
            if (mp[s[i]]%2 == 0) {
                res += mp[s[i]];
                mp[s[i]] = 0;
            }
        }
        for (auto x: mp) {
            if (x.second == 1) {
              res ++;
              break;
            }  
        }
        return res;
    }
};




Related Posts

Find Duplicate Subtrees Problem

LeetCode 652. Given the rootof a binary tree, return all...

Delete And Earn Problem

LeetCode 740. You are given an integer array nums. You...

Degree Of An Array Problem

LeetCode 697. Given a non-empty array of non-negative integers nums,...

Custom Sort String Problem

LeetCode 791. You are given two strings order and s....

Basic Calculator IV Problem

LeetCode 770. Given an expression such as expression = “e...

Sort Characters By Frequency Problem

LeetCode 451. Given a string s, sort it in decreasing...