Java Solution using LinkedHashMap, not the fastest but it is a good use of the property of LinkedHashMap in java

  • 0

    LinkedHashMap can keep the entries in insertion order. If one character with no duplicates is found in the map, its index is the smallest one.

    public class Solution {
    public int firstUniqChar(String s) {
        Map<Character, Integer> dict = new LinkedHashMap<>();
        char[] charArr = s.toCharArray();
        for(int i = 0;i<charArr.length;i++){
                dict.put(charArr[i],-1);//use -1 to mark duplicates
                dict.put(charArr[i],i);//else store the index
        Set keys = dict.keySet();
        for(Object key:keys){
                return dict.get(key);
        return -1;

Log in to reply

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