1. 程式人生 > >[LeetCode] 409. Longest Palindrome

[LeetCode] 409. Longest Palindrome

題:https://leetcode.com/problems/longest-palindrome/description/

題目

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.

題目大意

計算一組字元集合可以組成的迴文字串的最大長度

思路

1.計算 字串中,每個字元的 對數。在迴文字元中,成對的數放入。
2.若由字元對數 組成的 迴文字元 長度小於 原字串,則 可以有個單獨字元 作為 迴文串的中心。

class Solution {
    public int longestPalindrome(String s) {
        Map<Character,Integer> map = new HashMap();
        for(char c : s.toCharArray())
            map.put(c,map.getOrDefault(c,0)+1);
        int res = 0;
        int center = 0;
        for(char c : map.keySet()){
            res +=
map.get(c)/2; } res = res<<1; if(res<s.length()) res++; return res; } }