forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirst_unique_char.py
More file actions
41 lines (32 loc) · 1.03 KB
/
first_unique_char.py
File metadata and controls
41 lines (32 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""
First Unique Character in a String
Given a string, find the first non-repeating character and return its index.
If no unique character exists, return -1.
Reference: https://leetcode.com/problems/first-unique-character-in-a-string/
Complexity:
Time: O(n^2) worst case due to nested comparisons
Space: O(n) for the banned list
"""
from __future__ import annotations
def first_unique_char(text: str) -> int:
"""Find the index of the first non-repeating character in a string.
Args:
text: The input string to search.
Returns:
The index of the first unique character, or -1 if none exists.
Examples:
>>> first_unique_char("leetcode")
0
"""
if len(text) == 1:
return 0
banned: list[str] = []
for index in range(len(text)):
if (
all(text[index] != text[other] for other in range(index + 1, len(text)))
and text[index] not in banned
):
return index
else:
banned.append(text[index])
return -1