Java solution with HashMap


  • 0
    A

    The idea is to store the character of this string with its index. While traversing the string, if there is a duplicate, change the index to the length.

    After that, find the first element whose value is not changed. Then that value will be the index of the first unique character.

    public int firstUniqChar(String s) {
            HashMap<Character, Integer> hm = new HashMap<Character,Integer>();
            int l = s.length();
    
            for (int i = 0; i < l; i++) {
            	char c = s.charAt(i);
            	//Store the character with its index
            	if (!hm.containsKey(c)) {
            		hm.put(c,i);
            	}
            	//If there is a duplicate, change the value to l
            	else {
            		hm.put(c,l);
            	}
            }
    
            for (int i = 0; i < l; i++) {
            	//If the value is not l, then the value will be the location
            	if (hm.containsValue(i)) {
            		return i;
            	}
            }
            return -1;
        }
    

Log in to reply
 

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