Java Solution with O(n) time complexity and O(n) space complexity


  • 0
    Q
    class Solution {
        public int firstUniqChar(String s) {
           HashMap<Character, Integer> map = new HashMap<>();
            List<Integer> list = new ArrayList<>();
            for(int i = 0 ; i < s.length(); i++){
                if(map.containsKey(s.charAt(i))){
                    map.put(s.charAt(i), Integer.MAX_VALUE);
                }else{
                    map.put(s.charAt(i), i);
                    list.add(i);
                }
            }
            for(int i = 0; i < list.size(); i++){
                if(map.get(s.charAt(list.get(i))) != Integer.MAX_VALUE){
                    return list.get(i);
                }
            }
            return -1;
        }
    }
    

Log in to reply
 

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