LeetCode 0387. First Unique Character in a String Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0387. First Unique Character in a String

Description

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

 

Example 1:

Input: s = "leetcode"

Output: 0

Explanation:

The character 'l' at index 0 is the first character that does not occur at any other index.

Example 2:

Input: s = "loveleetcode"

Output: 2

Example 3:

Input: s = "aabb"

Output: -1

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.

Solutions

Solution 1: Counting

We use a hash table or an array of length 26 cnt to store the frequency of each character. Then, we traverse each character s[i] from the beginning. If cnt[s[i]] is 1, we return i.

If no such character is found after the traversal, we return -1.

The time complexity is O(n), where n is the length of the string. The space complexity is O(|Σ|), where Σ is the character set. In this problem, the character set consists of lowercase letters, so |Σ|=26.

PythonJavaC++GoTypeScriptJavaScriptPHP
class Solution: def firstUniqChar(self, s: str) -> int: cnt = Counter(s) for i, c in enumerate(s): if cnt[c] == 1: return i return -1(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !