Java use HashMap solution


  • 0
    T

    Use HashMap to record index of each char. If the char is duplicated, change the index to MAX_VALUE. Then get the lowest index from map.

    public int firstUniqChar(String s) {
        int res = Integer.MAX_VALUE;
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for (int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if (map.containsKey(c)){
                map.put(c, Integer.MAX_VALUE);
            }else{
                map.put(c, i);
            }
        }
        for (char c : map.keySet()){
            res = Math.min(res, map.get(c));
        }
        if (res == Integer.MAX_VALUE)//corner case: if there is no unique char
            return -1;
        return res;
    }

Log in to reply
 

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