每天一道LeetCode--409 .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) {
        int size = s.length();
        if (size == 0 || s == null)
            return 0;
        Map<Character,Integer> map = new HashMap<>();
        for (int i = 0; i < size; i++) {
            if (map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i),map.get(s.charAt(i))+1);
            } else {
                map.put(s.charAt(i), 1);
            }
        }
        int result=0;
        boolean flag=false;
        for(char c:map.keySet()){
            int f=map.get(c);
            if(f%2==0){
                result+=f;
            }else{
                flag=true;
                result+=f-1;
            }
        }
        return result+(flag?1:0);
    }
}

 

posted @ 2016-11-28 10:05  破玉  阅读(552)  评论(0编辑  收藏  举报