Java O(n) Solution with HashMap


  • 0
    Z

    For this question, we only care about the frequency of each character since we only wanna know the maximum length.

    public class Solution {
        public int longestPalindrome(String s) {
            if (s == null || s.length() == 0) return 0;
            Map<Character, Integer> map = new HashMap<>();
            int maxOddLength = Integer.MIN_VALUE;
            for (char c : s.toCharArray()) {
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
            int result = 0;
            boolean hasOddFrequency = false;
            for (char c : map.keySet()) {
                int freq = map.get(c);
                if (freq % 2 == 0) {
                    result += freq;
                } else {
                    hasOddFrequency = true;
                    result += freq - 1;
                }
            }
            // We can only allow one character that exists odd number of times within
            // a panlindrome
            return result + (hasOddFrequency ? 1 : 0);
        }
    }
    

Log in to reply
 

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