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.

 


题目标签:Hash Table

  题目给了我们一个string s,让我们找到在这个s 里 最长可能性的回文的长度。

  利用HashMap 先把 s 里的所有char 和它出现次数 做记录,然后遍历map 的keySet,把所有char 长度是偶数的加起来,在把所有char 长度是奇数的 - 1 加起来,最后要判断一下,如果有出现过奇数长度的char,那么在最后答案上再 + 1。

 

 

Java Solution:

Runtime beats 58.91% 

完成日期:06/06/2017

关键词:HashMap

关键点:对于奇数长度的char,我们也需要把它的 长度 - 1 累加

 1 class Solution 
 2 {
 3     public int longestPalindrome(String s) 
 4     {
 5         HashMap<Character, Integer> map = new HashMap<>();
 6         int len = 0;
 7         boolean oddChar = false;
 8         
 9         for(char c: s.toCharArray())
10             map.put(c, map.getOrDefault(c, 0) + 1);
11         
12         
13         for(char c: map.keySet())
14         {
15             int temp_len = map.get(c);
16             
17             if(temp_len % 2 == 0) // even len
18                 len += temp_len;
19             else // odd len
20             {
21                 if(!oddChar)
22                     oddChar = true;
23                 
24                 len += temp_len - 1;
25             }
26         }
27         
28         return oddChar ? len + 1 : len;
29     }
30 }

参考资料:N/A

 

LeetCode 题目列表 - LeetCode Questions List

posted @ 2017-11-08 06:00  Jimmy_Cheng  阅读(170)  评论(0编辑  收藏  举报