0409 - Longest Palindrome

0409 - 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.

Examples

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

Input: s = "a" Output: 1

Input: s = "bb" Output: 2

Constraints

  • 1 <= s.length <= 2000

  • s consists of lowercase and/or uppercase English letters only.

Java Solution

class Solution {
    public int longestPalindrome(String s) {

        int[] letterCount = new int[128];
        
        for(int i = 0; i < s.length(); i++) 
            letterCount[s.charAt(i)]++;

        int result = 0;
        
        boolean hasSingle = false;
        
        for(int num : letterCount) {
            if(num % 2 == 0) 
                result += num;
            else if(num >= 3) {
                result += num - 1;
                hasSingle = true;
            } 
            else hasSingle = true;
        }
        if(hasSingle) result++;
        
        return result;
    }
}

Last updated