Easy & fast java solution


  • 0
    D
    public class Solution {
        public int firstUniqChar(String s) {
            
            //Base case: if string is empty or null, return -1
            if(s.length()==0 || s==null)
                return -1;
                
            //hashmap to store # of occurences of each character
            HashMap<Character,Integer> map=new HashMap<Character,Integer>();
            
            //for loop to iterate through the string
            for(int i=0;i<s.length();i++)
            {
                if(map.containsKey(s.charAt(i)))
                {
                    int value=map.get(s.charAt(i));
                    map.put(s.charAt(i),++value);
                }
                else
                    map.put(s.charAt(i),1);
            }
            
            //see which character has only one occurence
            for(int i=0;i<s.length();i++)
            {
                if(map.get(s.charAt(i))==1)
                    return i;
            }
            
            //if none are present return -1
            return -1;
            
            
        }
    }
    
    

Log in to reply
 

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