Java Solution using Hashmap


  • 0
    U
    public int firstUniqChar(String s) {
            //save unique element in map<character,index>
            HashMap<Character,Integer> map = new HashMap<Character,Integer>();
            HashSet<Character> set = new HashSet<Character>();
            for (int i = 0; i < s.length(); i ++) {
                if(set.contains(s.charAt(i))) continue;
                if(map.containsKey(s.charAt(i))) {
                    map.remove(s.charAt(i));
                    set.add(s.charAt(i));
                }
                else { map.put(s.charAt(i),i);}
            }
            if(map.isEmpty()) return -1;
            
            //find first in unique char set
            int minIndex = Integer.MAX_VALUE;
            Collection<Integer> co = map.values();
            for (Integer index:co ) {  
                if (index < minIndex) minIndex = index;
            }  
            return minIndex;
        }
    

Log in to reply
 

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