728x90
from collections import Counter
class Solution:
def firstUniqChar(self, s: str) -> int:
idx = -1
c = Counter(s)
# print(c)
idx_list = []
for k,v in c.items():
# print(k,v)
if v == 1:
idx = s.index(k)
return idx
else:
return idx
Counter 클래스를 사용해서 풀었다.
counter를 찍어보니
Counter({'e': 3, 'l': 1, 't': 1, 'c': 1, 'o': 1, 'd': 1})
이런식으로 value 순으로 descending order로 출력은 되는데
실제 items로 iterate 해보면
입력순으로, 즉,
l,e,t,c,o,d 이렇게 출력된다.
++
string에서의 index위치를 파악할때는 string.index(substring) 이런식으로 사용하면 된다.
str.index(sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found.
str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
str.index VS. str.find
--> str.find를 쓰는게 safer option.
다른 풀이
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
lookup = defaultdict(int)
candidtates = set()
for i, c in enumerate(s):
if lookup[c]:
candidtates.discard(lookup[c])
else:
lookup[c] = i+1
candidtates.add(i+1)
return min(candidtates)-1 if candidtates else -1
728x90
'Leetcode' 카테고리의 다른 글
| [LeetCode] Is Subsequence 파이썬 (pointer, relative position) (0) | 2021.04.15 |
|---|---|
| [LeetCode] Find the Difference 파이썬 (Counter, A.subtract(B), bit operation, xor, reduce) (0) | 2021.04.14 |
| [LeetCode] Ransom Note 파이썬 (dict, set, count) (0) | 2021.04.14 |
| [LeetCode] Guess Number Higher or Lower 파이썬 (binary search) (0) | 2021.04.14 |
| [LeetCode] Valid Perfect Square 파이썬 (Binary Search, +Lower Bound) (0) | 2021.04.14 |
댓글