Version I - three for loops

public class Solution {

    public int longestPalindrome(String s) {
        //validate input

        Map<Character, Integer> map = new HashMap<>();//key - character, value - times of appearence 

        for (char c : s.toCharArray()) {
            if (!map.containsKey(c)) {
                map.put(c, 0);
            }

            map.put(c, map.get(c) + 1);

        }

        int result = 0;
        for (char c : map.keySet()) {
            if (map.get(c) / 2 != 0) {
                int count = (map.get(c) / 2) * 2;
                result += count;
                map.put(c, map.get(c) - count);
            } 
        }

        for (char c : map.keySet()) {
            if (map.get(c) == 1) {
                result++;
                break;
            }
        }

        return result;
    }
}

Version II - shorter

    public int longestPalindrome(String s) {

        Map<Character, Integer> map = new HashMap<>();//key - character, value - times of appearence 

        int result = 0;
        for (char c : s.toCharArray()) {
            if (!map.containsKey(c)) {
                map.put(c, 0);
            }

            map.put(c, map.get(c) + 1);

            if (map.get(c) == 2) {
                result += 2;
                map.put(c, map.get(c) - 2);
            }
        }

        for (char c : map.keySet()) {
            if (map.get(c) == 1) {
                result++;
                break;
            }
        }

        return result;
    }

results matching ""

    No results matching ""