409. Longest Palindrome

来源:互联网 发布:mac虚拟机安装教程 编辑:程序博客网 时间:2024/05/16 18:29

原题网址: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:7Explanation: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);    }}


0 0