题目地址:https://leetcode.com/problems/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 LongestPalindrome {
public int longestPalindrome(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
if (!map.containsKey(s.charAt(i))) {
map.put(s.charAt(i), 1);
} else {
map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
}
}
System.out.println(map);
int len = 0;
boolean isOdd = false;
for (Map.Entry e: map.entrySet()) {
if ((int)e.getValue() % 2 == 1 )
isOdd = true;
len += ((int)e.getValue() / 2) * 2;
}
if (isOdd)
len++;
return len;
}
public static void main(String[] args) {
LongestPalindrome longestPalindrome = new LongestPalindrome();
System.out.println(longestPalindrome.longestPalindrome("abccccdd"));
}
}
以上实现效率稍稍差了些,因为首先花了O(n)的时间遍历了一次字符串,然后又遍历了一次map,map的大小是由字符串中字符的重复程度决定的,最差情况也就是字符串中没有重复字符,那么遍历map的时间复杂度也是O(n)。