Java solution with O(n) space complexity using a HashMap


  • 0
    S
    public int firstUniqChar(String s) {
            HashMap<Character, Integer> map = new HashMap<Character,Integer>();
            for(int i=0; i< s.length(); i++)
            {
             if(map.containsKey(s.charAt(i)))
                 map.put(s.charAt(i), map.get(s.charAt(i))+1);
                else
                 map.put(s.charAt(i),1);
            }
           for(int i=0;i< s.length();i++)
           {
            if(map.containsKey(s.charAt(i)) && map.get(s.charAt(i)) == 1 )
                return i;
           }
           return -1; 
        }
    A simple code with HashMap for storing the frequency of letters and then iterating through the string to find out the letter that occurs first with a frequency of 1.

Log in to reply
 

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