프로그래밍/LeetCode
[LeetCode][Python3] 387. First Unique Character in a String
snoopybox
2018. 11. 5. 23:46
Problem :
https://leetcode.com/problems/first-unique-character-in-a-string/
My Solution :
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
counter = [0]*26
for c in s:
counter[ord(c)-97] += 1
for i, c in enumerate(s):
if counter[ord(c)-97] == 1:
return i
return -1
Comment :
알파벳 소문자라는 제약이 있기 때문에 이렇게 풀었다. Dictionary를 활용한 버전은 살짝 바꾼 아래와 같다.
My Solution2 :
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
counter = dict()
for c in s:
counter[c] = counter.get(c, 0) + 1
for i, c in enumerate(s):
if counter.get(c, 0) == 1:
return i
return -1