天天一道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.ide

This is case sensitive, for example "Aa" is not considered a palindrome here.ui

Note:
Assume the length of given string will not exceed 1,010.spa

 Example:code

Input:
"abccccdd"

Output:
7

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

解決方法:blog

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);
    }
}
相關文章
相關標籤/搜索