Um momento
Leetcode / 387. First Unique Character in a String

Pick a programming language:

Here is the source code for the solution to this problem.

import java.util.HashMap;
// import java.util.HashSet;

class Solution {
    // time O(N)
    // space O(N)
    public int firstUniqChar(String s) {
        HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();

        for (int i = 0; i < s.length(); i++) {
            if (hashMap.containsKey(s.charAt(i))) {
                hashMap.put(s.charAt(i), hashMap.get(s.charAt(i)) + 1);
            }
            else {
                hashMap.put(s.charAt(i), 1);
            }
        }

        for (int i = 0; i < s.length(); i++) {
            if (hashMap.get(s.charAt(i)) == 1) {
                return i;
            }
        }

        return -1;
    }

    // time O(N^2)
    // space O(N)
    // public int firstUniqChar(String s) {
    //     HashSet<Character> hashSet = new HashSet<Character>();
    //     outerloop:
    //     for (int i = 0; i < s.length(); i++) {
    //         if (hashSet.contains(s.charAt(i))) {
    //             continue;
    //         }
    //         else {
    //             hashSet.add(s.charAt(i));
    //         }
    //         for (int j = i + 1; j < s.length(); j++) {
    //             if (s.charAt(i) == s.charAt(j)) {
    //                 continue outerloop;
    //             }
    //         }
    //         return i;
    //     }

    //     return -1;
    // }
}
Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: