clueless coding // TODO: be smarter

LeetCode Find the Difference: Java Solution



TL;DR Code Solution


public char findTheDifference(String s, String t) {

    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);
    }

    for (int i = 0; i < t.length(); i++) {
        char cur = t.charAt(i);
        if (!hashMap.containsKey(cur) || hashMap.get(cur) == 0) {
            return cur;
        }
        else {
            hashMap.put(cur, hashMap.get(cur) - 1);
        }
    }

    return 'd';

}