Easy understand Java Solution


  • 0
    U
       public int longestPalindrome(String s) {
            HashMap<Character, Integer> map = new HashMap<Character, Integer>();
            int count = 0;
            char[] a = s.toCharArray();
            // count the char frequency
            for(char i : a){
                if(map.containsKey(i))
                    map.put(i, map.get(i)+1);
                else
                    map.put(i,1);
            }
            boolean containsOdd = false;
             
            for(char i : map.keySet()){
                if(map.get(i) % 2 == 0)
                    count += map.get(i);// we can use the whole even freq char
                else{
                    count += map.get(i)-1;// 
                    containsOdd = true;
                }
                    
            }
            return containsOdd ? count+1 : count;
            
        }

Log in to reply
 

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