码迷,mamicode.com
首页 > 其他好文 > 详细

409. Longest Palindrome

时间:2017-10-23 21:41:02      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:sum   letter   含义   interview   大小   class   blog   his   get   

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     public int longestPalindrome(String s) {
 2         if (s.isEmpty()) return 0;
 3         Map<Character, Integer> map = new HashMap<>();
 4         for (int i = 0; i < s.length(); i++) {
 5             Character letter = s.charAt(i);
 6             map.put(letter, map.getOrDefault(letter, 0) + 1);
 7         }
 8         int sum = 0;
 9         int haveOgg = 0;
10         for (Map.Entry<Character, Integer> entry : map.entrySet()) {
11             int count = entry.getValue();
12             if (count % 2 == 0) sum += count;
13             else {
14                 haveOgg = 1;
15                 sum += count - 1;
16             }
17         }
18         return sum + haveOgg;        
19     }

 

 

 

 

409. Longest Palindrome

标签:sum   letter   含义   interview   大小   class   blog   his   get   

原文地址:http://www.cnblogs.com/wzj4858/p/7718856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!