Java solution, using only one array int[52]


  • 0
    E
    public class Solution {
        public int longestPalindrome(String s) {
            int [] arr = new int[52];
            for(int k=0;k<s.length();k++){
                char c = s.charAt(k);
                int index = 0;
                if(c>='a'){
                    index = (int)(c-'a')+26;
                    
                }else{
                    index = (int)(c-'A');
                }
                arr[index] += 1;
            }
            
            int max = 0;
            for(int k=0;k<arr.length;k++){
                int count = arr[k];
                if(count>0&&count%2==0){
                    max += count;
                }else if(count>1){
                    max += count-1;
                }
            }
            
            if(max == s.length())
            return max;
            
            return max + 1;
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.