409. Longest Palindrome

原題網址:https://leetcode.com/problems/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.

Example:

Input:
"abccccdd"

Output:
7

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

方法:直方圖頻率統計。

public class Solution {
    public int longestPalindrome(String s) {
        char[] sa = s.toCharArray();
        int[] frequency = new int[52];
        for(char ch : sa) {
            if ('A' <= ch && ch <= 'Z') {
                frequency[ch - 'A'] ++;
            } else {
                frequency[ch - 'a' + 26] ++;
            }
        }
        boolean single = false;
        int len = 0;
        for(int f : frequency) {
            single |= (f & 1) == 1;
            len += f / 2;
        }
        return len * 2 + (single ? 1 : 0);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章