My solution in Java with O(N)


  • 0
    A
    public class Solution
    {
        public int longestPalindrome(String s)
        {
            int count = 0;
            boolean hasOdd = false;
            HashMap<Character, Integer> hm = new HashMap<>();
            for(int i = 0; i < s.length(); i++)
            {
                int newCount = hm.getOrDefault(s.charAt(i), 0);
                ++newCount;
                hm.put(s.charAt(i), newCount);
            }
            Set keys = hm.keySet();
            Iterator it = keys.iterator();
            while(it.hasNext())
            {
                int value = hm.get(it.next());
                if(value > 0 && value % 2 == 0)
                    count += value;
                else
                {
                     count += value - 1;
                     hasOdd = true;
                }
            }
            return count + (hasOdd ? 1 : 0);
        }
    }
    

Log in to reply
 

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