clueless coding // TODO: be smarter

LeetCode First Unique Character in a String: Java Solution



TL;DR Code Solution


public int firstUniqChar(String s) {

    HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
    for (int i = 0; i < s.length(); i++) {

        char cur = s.charAt(i);

        if (!hashMap.containsKey(cur)) {
            hashMap.put(cur, 1);
        }
        else {
            hashMap.put(cur, hashMap.get(cur) + 1);
        }

    }

    for (int i = 0; i < s.length(); i++) {

        char cur = s.charAt(i);
        if (hashMap.get(cur) == 1) {
            return i;
        }


    }

    return -1;
}