跳转至

409. Longest Palindrome

Leetcode Hash Table

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.

分析

最长回文。使用哈希表存储,这里由于存储对象是字母,所以可以用长128的数组存储(ascii表长度为128)。

public int longestPalindrome(String s) {
    if (s == null || s.length() == 0) return 0;

    int [] count = new int[128];
    int res = 0;
    for (char c: s.toCharArray())
        count[c]++;

    for (int i = 0; i < 128; i++)
        res += count[i]/2;

    res *= 2;
    if (res < s.length()) res++;

    return res;
}