simple hashMap solution


  • 0
    U

    We need a hashmap to store the numbers of the occurrences of all characters. We then need to iterate the string twice. First iteration : count the occurrences for each character.
    second one : from the first char to the last one , return the one with count 1 immediately.

    class Solution {
        public int firstUniqChar(String s) {
            if (s == null || s.length() == 0) {
                return -1;
            }
            Map<Character , Integer> m = new HashMap<>();
            for(char i : s.toCharArray()) {
                if (!m.containsKey(i)) {
                    m.put(i , 1);
                } else {
                    m.put( i , m.get(i) + 1);
                }
            }
            for (int i = 0 ; i < s.length() ;i++) {
                if(m.get(s.charAt(i)) == 1) {
                    return i;
                }
            }
            return -1;
        }
    }
    

Log in to reply
 

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