Title: Longest palindrome string


Given a string containing both uppercase and lowercase letters, find the longest palindrome string constructed from these letters. Pay attention to case sensitivity during construction. For example, "Aa" cannot be treated as a palindrome string.Copy the code

Example:


Input: "abccCCdd" Output: 7 Explanation: The longest palindrome string we can construct is "dCCaccd ", which is 7 in length.Copy the code

Think about:


This problem uses a Map to record the number of occurrences of each character. Then, the Map is traversed. If the number of times is even, the result can be added; if the number of times is odd, the result can be added after the number is reduced by 1. Use a Boolean to record whether there are elements of odd degree. After the Map is traversed, if there are odd degree elements, you can place an odd degree number in the middle of the string and add one to the palindrome string length.Copy the code

Implementation:


class Solution { public int longestPalindrome(String s) { int result = 0; boolean isHas = false; char[] strArray = s.toCharArray(); Map<Character, Integer> time = new HashMap(); for (int count = 0; count < strArray.length; count++) { if (time.get(strArray[count]) == null) { time.put(strArray[count], 1); } else { time.put(strArray[count], time.get(strArray[count]) + 1); } } Set<Character> set = time.keySet(); for (Character character : set) { int times = time.get(character); if (times % 2 == 0) { result += (times); } else if (times % 2 == 1) { isHas = true; result += ((times - 1)); } } if (isHas) { result += 1; } return result; }}Copy the code