Carregando

Problema do LeetCode#387

First Unique Character in a String

Resolvido em 1 linguagemJava

Resolver no LeetCode(abre em uma nova aba)

Solução

50 linhas
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}

Quer uma explicação desta solução em Java?

Receba uma explicação passo a passo da ideia por trás do código.

Todos os problemas

Os enunciados dos problemas pertencem ao LeetCode e estão em leetcode.com. Não temos vínculo com o LeetCode.