일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Easy
- Leedcode
- Hashtable
- 구현
- Two Pointers
- graph
- stack
- hash
- heap
- 광연자동차운전면허학원
- String
- LinkedList
- sorting
- A* Algorithm
- array
- SinglyLinkedList
- DailyLeetCoding
- greedy
- leetcode
- Bellman-Ford
- Union Find
- 자료구조
- ArrayList vs LinkedList
- BFS
- Java
- VCS
- hash table
- dfs
- python3
- Medium
Archives
- Today
- Total
Min IT's Devlog
[python3] 387. First Unique Character in a String 본문
풀이 일자: 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/
'코테 > LeetCode(Solve)' 카테고리의 다른 글
[python3] 967. Numbers With Same Consecutive Differences (0) | 2022.09.03 |
---|---|
[python3] 637. Average of Levels in Binary Tree (0) | 2022.09.03 |
[python3] 1448. Count Good Nodes in Binary Tree (0) | 2022.09.01 |
[python3] 1338. Reduce Array Size to The Half (0) | 2022.08.18 |
[python3] 804. Unique Morse Code Words (0) | 2022.08.17 |
Comments