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