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

X Of A Kind In A Deck Of Cards Problem

LeetCode 914. In a deck of cards, each card has...

Word Subsets Problem

LeetCode 916. You are given two string arrays words1 and...

Vowel Spellchecker Problem

LeetCode 966. Given a wordlist, we want to implement a...

Verifying An Alien Dictionary Problem

LeetCode 953. In an alien language, surprisingly, they also use...

Unique Morse Code Words Problem

LeetCode 804. International Morse Code defines a standard encoding where...

Unique Email Addresses Problem

LeetCode 929. Every valid email consists of a local name...