HashMap solution in Java


  • 0
    D
    public class Solution {
        public int longestPalindrome(String s) {
            if (s == null || s.length() == 0) {
                return 0;
            }
            Map<Character, Integer> count = new HashMap<>();
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                count.put(ch, count.containsKey(ch) ? count.get(ch) + 1 : 1);
            }
            int len = 0;
            boolean metodd = false;
            for (int freq : count.values()) {
                if (freq % 2 == 0) {
                    len += freq;
                } else if (metodd) {
                    len += freq / 2 * 2;
                } else {
                    metodd = true;
                    len += freq;
                }
            }
            return len;
        }
    }
    

Log in to reply
 

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