Java solution


  • 0
    T
    public class Solution {
        //Use the hash map to store the <character, index> pair. 
        //If the map.containsKey(current_character), let the value of this key be -1.
        //After construct the map, the map has keys from all the characters in s and if any character has duplications, the value of this key will be -1 else the value of this key is its index in s.
        //we iterate the map and find the smallest unique index.
        public int firstUniqChar(String s) {
            HashMap<Character, Integer> map = new HashMap<Character, Integer>();
            for(int i = 0; i < s.length(); i++){
                if (map.containsKey(s.charAt(i))){
                    //update the vaule of duplicated character.
                    map.put(s.charAt(i), -1);
                }
                else{
                    map.put(s.charAt(i), i);
                }
            }
            int output = Integer.MAX_VALUE;
            for(Character key : map.keySet() ){
                if(map.get(key) != -1 && output > map.get(key)){
                    output = map.get(key);
                }
            }
            if (output == Integer.MAX_VALUE){
                return -1;
            }
            else    return output;
        }
    }
    

Log in to reply
 

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