HashMap java


  • 0
    T

    Hashmap store the position of letters

    public class Solution {
        public int firstUniqChar(String s) {
            HashMap<Character,ArrayList<Integer>> dic=new HashMap<>();
            
            for(int i=0;i<s.length();i++){
                char c=s.charAt(i);
                if(!dic.containsKey(c)){
                    dic.put(c,new ArrayList<Integer>());
                }
                    dic.get(c).add(i);
            }
            
            for(int i=0;i<s.length();i++){
                if(dic.get(s.charAt(i)).size()==1){
                    return dic.get(s.charAt(i)).get(0);
                }
            }
            
            
            return -1;
            
        }
    }
    

Log in to reply
 

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