Java solution using HashMap


  • 0
    C
    class Solution {
        public int firstUniqChar(String s) {
            HashMap<Character, Integer> map = new HashMap<Character, Integer> ();
            int count = 0;
            int value = -1;
            for(char ch: s.toCharArray())
            {
             
                if (map.containsKey(ch))
                {
    
                    map.remove(ch);
                    map.put(ch,-2);
                }
                else
                {map.put(ch,count);}
                   count = count + 1;
            }
       for ( char key : map.keySet() ) { 
           if ((value == -1) && (map.get(key) != -2)) {
           value =  map.get(key);                      
           }
           if ((map.get(key) < value) && (map.get(key) != -2))
           {
                      value =  map.get(key);           
           }
    }     
            return value;
        }
    }
    

Log in to reply
 

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