Simple Java solution using HashMap


  • 0
    M
    public class Solution {
        public int longestPalindrome(String s) {
            //The trick is that in palindrome, there can be only character whose count(Number of occurrences) is odd.
            //so we just consider the sum of even value of each character and then add 1, if there is a character with odd number of appearences.
            Map<Character, Integer> map = new HashMap<>();
            Integer current = 0;
            //Construct map with the occurrences value.
            for( int i =0; i < s.length(); i++ )
            {
                char c = s.charAt(i);
                if( (current = map.get(c)) != null )
                {
                    map.put(c, current + 1 );
                }
                else
                {
                    map.put(c, 1);
                }
            }
            int result = 0, count;
            boolean oddOccur = false;
            for( Map.Entry<Character, Integer> entry : map.entrySet() )
            {
                count = entry.getValue();
                if( count % 2 == 0 )
                {
                    result += count;
                }
                else
                {
                 oddOccur = true;   
                 result += count - 1;
                }
            }
            if( oddOccur )
                result += 1;
            return result;
        }
    }
    

Log in to reply
 

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