Min IT's Devlog

[python3] 387. First Unique Character in a String 본문

코테/LeetCode(Solve)

[python3] 387. First Unique Character in a String

egovici 2022. 8. 16. 11:23

풀이 일자: 22.08.16

난이도: [Easy]

 

문제 내용

주어진 문자열 s안에서 1번만 나온 문자의 가장 첫번째 index를 반환하는 문제

 

문제 해결 흐름

1. 1번만 나오는 문자를 체크하기 위해서는 문자의 개수를 세야겠다. 

→ 중복은 하나로 처리해야하고 탐색도 해야하기 때문에 Dictionary(Hash)를 사용하면 좋겠다.

2.  가장 첫번째 index를 반환하려면 순서에 대한 정보를 가지고 있어야겠다.

→  새로운 문자가 들어올때마다 append로 넣고 동일한 문자가 들어오면 remove로 없앨 수 있도록 list를 사용하자.

3. 첫번째 index를 찾자

→  str.find()를 이용하여 찾고 만약에 candidate가 비었다면 다 중복이 있다는 이야기임으로 -1을 리턴하자.

class Solution:
    def firstUniqChar(self, s: str) -> int:
        existTable = dict()
        candidate = list()
        for i in range(0,len(s)):
            if s[i] not in existTable:
                candidate.append(s[i])
                existTable[s[i]] = 1
            else:
                if s[i] in candidate:
                    candidate.remove(s[i])
                    
        return s.find(candidate[0]) if candidate else -1

다른 해결 방식

1. collections의 Counter를 사용한다면 더 쉽게 해결 가능하지 않을까?

→ Counter를 통해 세는 과정이 축약될 것이다.

class Solution:
    def firstUniqChar(self, s: str) -> int:
    	counter = Counter(s)
        for i, data in enumerate(s):
        	if counter[data] == 1:
            	return i
        return -1

문제 링크

https://leetcode.com/problems/first-unique-character-in-a-string/

Comments