Java solution using MAP


  • 0
    S

    Two maps are used here. The first map's key are all the characters and other map's keys are those which are unique. The values represent the position of the character. Next, by finding the minimum value we get the required minimum position.

    (Definitely not the best solution there.)

        public int firstUniqChar(String s) {
            if(s.length()==0){
                return -1;
            }
            Map<Character, Integer> m = new HashMap<Character, Integer>();
    		Map<Character, Integer> m2 = new HashMap<Character, Integer>();
    		int min = Integer.MAX_VALUE;
    		for(int i = 0; i < s.length(); i++){
    			if(m.containsKey(s.charAt(i))){
    				m2.remove(s.charAt(i));
    			} else {
    				m.put(s.charAt(i), i);
    				m2.put(s.charAt(i), i);
    			}
    		}
    		for(int n : m2.values()){
    			min = Math.min(min,n);
    		}
    		return min = (min==Integer.MAX_VALUE)?-1:min;
        }
    }

Log in to reply
 

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