Tags: "leetcode", access_time 1-min read

Edit this post on Github

First Unique Character in a String

Created: March 15, 2020 by [lek-tin]

Last updated: March 15, 2020

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

Example 1

s = "leetcode"
return 0.

Example 2

s = "loveleetcode",
return 2.

Solution

Java

class Solution {
    public int firstUniqChar(String s) {
        int[] counter = new int[256];
        for ( char c: s.toCharArray() ) {
            counter[c] += 1;
        }

        for ( int i = 0; i < s.length(); i++) {
            if (counter[s.charAt(i)] == 1) {
                return i;
            }
        }

        return -1;
    }
}

Python

from collections import Counter

class Solution:
    def firstUniqChar(self, s: str) -> int:
        counter = Counter(list(s))

        for i in range(len(s)):
            if counter[s[i]] == 1:
                return i

        return -1