Description:
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.
Accepted 108,427 Submissions 222,684
Solution:
class Solution { public int longestPalindrome(String s) { if(s==null||s.length()==0){ return 0; } int[] character_count = new int[123]; for(int i = 0; i<s.length(); i++){ int pos = (int) s.charAt(i); //System.out.println(pos); if(character_count[pos]==0){ character_count[pos]=1; } else{ character_count[pos] = character_count[pos]+1; } } int sum = 0; int max_odd = 0; boolean check_flag = false; for(int i = 0; i<character_count.length; i++){ if(character_count[i]!=0){ //System.out.println(character_count[i]); if(character_count[i]%2==0){ sum = sum +character_count[i]; character_count[i] =0; check_flag = true; } else{ if(character_count[i]>max_odd){ max_odd = character_count[i]; } sum = sum+ character_count[i]-1; } } } if(max_odd>=1){ sum = sum +1; } if(!check_flag){ sum = max_odd; } return sum ; } }