Loading

LeetCode problem#387

First Unique Character in a String

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

50 lines
1import java.util.HashMap;
2// import java.util.HashSet;
3
4class Solution {
5    // time O(N)
6    // space O(N)
7    public int firstUniqChar(String s) {
8        HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
9
10        for (int i = 0; i < s.length(); i++) {
11            if (hashMap.containsKey(s.charAt(i))) {
12                hashMap.put(s.charAt(i), hashMap.get(s.charAt(i)) + 1);
13            }
14            else {
15                hashMap.put(s.charAt(i), 1);
16            }
17        }
18
19        for (int i = 0; i < s.length(); i++) {
20            if (hashMap.get(s.charAt(i)) == 1) {
21                return i;
22            }
23        }
24
25        return -1;
26    }
27
28    // time O(N^2)
29    // space O(N)
30    // public int firstUniqChar(String s) {
31    //     HashSet<Character> hashSet = new HashSet<Character>();
32    //     outerloop:
33    //     for (int i = 0; i < s.length(); i++) {
34    //         if (hashSet.contains(s.charAt(i))) {
35    //             continue;
36    //         }
37    //         else {
38    //             hashSet.add(s.charAt(i));
39    //         }
40    //         for (int j = i + 1; j < s.length(); j++) {
41    //             if (s.charAt(i) == s.charAt(j)) {
42    //                 continue outerloop;
43    //             }
44    //         }
45    //         return i;
46    //     }
47
48    //     return -1;
49    // }
50}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.