p409

LeetCode p409 Longest Palindrome 题解

1.题目:

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.

题意:

输入一个字符串,求用这个字符串中的字符可以组成的最长回文字符串的长度。

2.解题思路:

HashMap储存相同字符的个数。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
public class Solution {
public int longestPalindrome(String s) {
int flag = 0;
int ans = 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}

for (char c : map.keySet()) {
int k = map.getOrDefault(c, 0);
ans = ans + (k / 2) * 2;
if (k % 2 == 1)
flag = 1;
}
return ans + flag;
}
}

4.一些总结: