387. First Unique Character in a String (Easy)

https://leetcode.com/problems/first-unique-character-in-a-string/

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

Solutions

class Solution {
    public int firstUniqChar(String s) {
        if (s ==  null || s.length() == 0) {
            return -1;
        }

        // Keep the count of each character, and the key should be sorted in the
        // order it is inserted.
        Map<Character, Integer> countMap = new LinkedHashMap<>();

        // Keep the position of the first occurrence of each character.
        Map<Character, Integer> positionMap = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);

            if (!countMap.containsKey(c)) {
                countMap.put(c, 0);
            }

            countMap.put(c, countMap.get(c) + 1);

            if (!positionMap.containsKey(c)) {
                positionMap.put(c, i);
            }
        }

        for (Character c : countMap.keySet()) {
            if (countMap.get(c) == 1) {
                return positionMap.get(c);
            }
        }

        return -1;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:18

results matching ""

    No results matching ""