Thursday, January 25, 2018

[2018-Interview] First Unique Character in a String

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


My answer: Tried to find a solution using only 1 single loop, but failed.



class Solution {
    public int firstUniqChar(String s) {
        // Solution 1
        Map<Character, Integer> charCountMap = new HashMap<Character, Integer>();
        for (int i = 0; i < s.length(); i ++) {
            Integer count = charCountMap.getOrDefault(s.charAt(i), 0);
            count += 1;
            charCountMap.put(s.charAt(i), count);
        }
        for (int i = 0; i < s.length(); i ++) {
            if (charCountMap.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        
        return -1;
    }
}

No comments:

Post a Comment