409. Longest Palindrome

Posted 鱼与海洋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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) {
      HashMap<Character, Integer> map = new HashMap<>();
      int res = 0;
      int odd = 0;
      for(int i = 0; i < s.length(); i++){
          map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0)+1);
      }
      for(int i : map.values()){
          if(i > 0 &&  i % 2 == 0)
            res += i;
          else{
            res += i - 1;  //是奇数的话要可取偶数个值!!!!
            odd = 1;
          }
      }
      return res + odd;
    }
}

 

以上是关于409. Longest Palindrome的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 409 Longest Palindrome

[leetcode-409-Longest Palindrome]

LeetCode——409. Longest Palindrome

409. Longest Palindrome

409. Longest Palindrome

409. Longest Palindrome