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 Solution { public int longestPalindrome(String s) { if(s == null || s.length() == 0) return 0; int[] low = new int[26]; int[] up = new int[26]; char[] chars = s.toCharArray(); for (char c : chars) { if(c - 'a' < 0) up[c-'A']++; else low[c-'a']++; } int odd = 0; int res = 0; for (int i = 0; i < 26; i++) { if(up[i] % 2 == 0) res += up[i]; else { res += up[i] - 1; odd = 1; } if(low[i] % 2 == 0) res += low[i]; else { odd = 1; res += low[i] - 1; } } if(odd == 1) res++; return res; }}新闻热点
疑难解答