JAVA AC solution, 1-pass with comment explanation


  • 0
    H
    class Solution {
        public int firstUniqChar(String s) {
            int min = Integer.MAX_VALUE; //to get minimum index 
            Map<Character, Integer> map = new HashMap<>(); // character 'a' to 'z' would be the key for this map in worst case
            char[] c= s.toCharArray(); 
            for(int i=0;i<c.length;i++)
            {
                if(map.containsKey(c[i]) && map.get(c[i])>-1) // check if the map element is present and visited
                    map.put(c[i],(map.get(c[i])+1)*-1); // if element is present and not visited, make it negative to make it visited
                                                        //  (map.get(c[i])+1) => +1 is added sothat it would work for element in zeroth position               
                else if(!map.containsKey(c[i]))
                    map.put(c[i],i); 
            }
            for(int v : map.values())
                min = (v>-1)? Math.min(min,v) : min ; //  get the minimum index
            return (min<Integer.MAX_VALUE)? min : -1;
        }
    }
    

Log in to reply
 

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