409. Longest Palindrome

Description

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.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

Solution

class Solution {
    public int longestPalindrome(String s) {
        int[] lower = new int[26];
        int[] upper = new int[26];
        
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) >= 'a') {   // 'a' > 'A'
                ++lower[s.charAt(i) - 'a'];
            } else {
                ++upper[s.charAt(i) - 'A'];
            }
        }
        
        int longestPalinLen = 0;
        for (int i = 0; i < 26; ++i) {
            longestPalinLen += (lower[i] / 2) * 2 + (upper[i] / 2) * 2;
        }
        
        // if s is not fully used, there exists odd char count
        return longestPalinLen == s.length() ? 
            longestPalinLen : longestPalinLen + 1;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容