AC JAVA Solution, Easy to understand


  • 0
    public class Solution {
        public int longestPalindrome(String s) {
            
            int res = 0;
            boolean hasOdd = false;
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            
            char[] arr = s.toCharArray();
            
            for (char c : arr)
            {
                if (!map.containsKey(c))
                {
                    map.put(c, 0);
                }
                map.put(c, map.get(c) + 1);
            }
            
            for (int k : map.values())
            {
                if ( k % 2 == 0)
                {
                    res = res + k;
                }
                else 
                {
                    res = res + k - 1;
                    hasOdd = true;
                }
               
            }
            if (hasOdd == true)
            {
                res ++;
            }
            return res;
        }
    }
    

Log in to reply
 

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