Java solution using HashMap with O(n) complexity


  • 0
    A

    This is the solution for "First unique Character in a String" using HashMap.

     public int firstUniqChar(String s) {
            Map<Character, Integer> map= new LinkedHashMap<>();
            Map<Character, Integer> mapOfIndex = new HashMap<>();
            char[] charArr = s.toCharArray();
            for(int i=0; i < charArr.length;i++) {
                if(map.containsKey(charArr[i])) {
                   map.put(charArr[i], map.get(charArr[i]) + 1);
                }else {
                    map.put(charArr[i], 1);
                    mapOfIndex.put(charArr[i], i);
                }     
            }
            
            for(char key : map.keySet()){  
                  if(map.get(key) == 1 ) {
                      return mapOfIndex.get(key);
                  }
            } 
            
            return -1;
        }
    
    

Log in to reply
 

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