Simple O(n) HashMap Java Solution


  • 0
    T

    Algorithm for first non repeated char:

    1. keep the count of character occurences
    2. iterate map and print where the value is 1(count ==1) and return index

    This code can also be modified to find first repeated char by returning where count >1

     public int firstUniqChar(String s) {
            Map<Character, Integer> hm = new HashMap<Character, Integer>();
            char[] input = s.toCharArray();
            for(char a : input){
                if(hm.containsKey(a))
                    hm.put(a,hm.get(a)+1);
                else
                    hm.put(a,1);
            }
            for(int a = 0; a< input.length;a++){
                if(hm.get(input[a])==1)
                    return a;
            }
            return -1;
        }
    
    

Log in to reply
 

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