clueless coding // TODO: be smarter

LeetCode Longest Palindrome: Java Solution



TL;DR Code Solution


public int longestPalindrome(String s) {

    HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();

    for (int i = 0; i < s.length(); i++) {
        char cur = s.charAt(i);
        hashMap.put(cur, hashMap.getOrDefault(cur, 0) + 1);
    }

    int result = 0;
    boolean hasOdd = false;
    for (int value : hashMap.values()) {

        if (value % 2 == 1 && hasOdd == false) {
            result += 1;
            hasOdd = true;
        }

        result += 2 * (value / 2);

    }
    return result;


}