Skip to content

Commit 46df664

Browse files
authored
Create 387-first_unique_character_in_str.py
1 parent f059ae2 commit 46df664

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

387-first_unique_character_in_str.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
https://leetcode.com/problems/first-unique-character-in-a-string/submissions/
3+
"""
4+
class Solution(object):
5+
6+
"""
7+
Brute force
8+
9+
Runtime: not very good
10+
"""
11+
def firstUniqChar(self, str):
12+
"""
13+
:type s: str
14+
:rtype: int
15+
"""
16+
for s in str:
17+
if str.count(s) == 1:
18+
return str.index(s)
19+
return -1
20+
21+
"""
22+
O(n) solution--using dictionary-equivalent DS
23+
24+
Runtime: 136 ms, faster than 65.45% of Python online submissions for First Unique Character in a String.
25+
Memory Usage: 13 MB, less than 85.64% of Python online submissions for First Unique Character in a String.
26+
"""
27+
def firstUniqChar(self, str):
28+
"""
29+
:type s: str
30+
:rtype: int
31+
"""
32+
counts = [0] * 26
33+
34+
#find counts for each
35+
for s in str:
36+
counts[ord(s) - ord('a')] += 1
37+
38+
for i, s in enumerate(str):
39+
if counts[ord(s) - ord('a')] == 1:
40+
return i
41+
return -1

0 commit comments

Comments
 (0)