Longest Palindrome

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

This is case sensitive, for example "Aa" is not considered a palindrome here.
  • Note:
Assume the length of given string will not exceed 1,010.
  • Examples:
Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
  • Analysis:
The longest palindrome is that all even count of all characters plus the longest odd count character.
  • Code - Java:
class Solution {
    public int longestPalindrome(String s) {
        int len = s.length();
        int result = 0;
        Map<Character, Integer> counts = new HashMap<Character, Integer>();
        for (int i = 0; i < len; i++) {
            char ch = s.charAt(i);
            int count = counts.getOrDefault(ch, 0) + 1;
            if (count == 2) {
                result++;
                counts.remove(ch);
            } else {
                counts.put(ch, count);
            }

        }
        return !counts.isEmpty() ? 2 * result + 1 : 2 * result;
    }
}
  • Code - C++:
class Solution {
public:
    int longestPalindrome(string s) {
        int len = s.length();
        int result = 0;
        map<char, int> counts;
        for (int i = 0; i < len; i++) {
            char ch = s[i];
            if (counts.find(ch) != counts.end()) {
                result++;
                counts.erase(ch);
            } else {
                counts.insert(pair<char, int>(ch, 1));
            }
        }
        return !counts.empty() ? 2 * result + 1 : 2 * result;
    }
};
  • Code - Python:
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        result = 0
        counts = {}
        for ch in s:
            if ch in counts:
                result += 1
                del(counts[ch])
            else:
                counts[ch] = 1
        if len(counts) != 0:
            return 2 * result + 1
        return 2 * result
  • Time Complexity: O(N), N is the length of string s.

  • Space Complexity: O(N), N is the length of string s.

results matching ""

    No results matching ""