Java solution of First Unique Character in a String

  • 0

    in the counting section, it used HashMap to count using char in the string as key, number of duplication as value.

    Time complexity is O(n)
    Space complexity is O(n)

    public int firstUniqChar(String s) {
            HashMap<Character, Integer> chars = new HashMap<>();
            for(char ch : s.toCharArray())
                chars.put(ch, chars.getOrDefault(ch, 0) + 1);
            for(int i = 0; i < s.length(); i++)
                if(chars.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.