일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 추석맞이 코딩챌린지
- 그리디
- KAKAO BLIND RECRUITMENT
- 정규식
- DateTime
- Re
- backjoon
- dfs
- 정렬
- 위클리 챌린지
- BFS
- 카카오
- 백준
- Combinations
- Set
- 다익스트라
- lambda
- 재귀함수
- divmod
- Zip
- 동적 계획법
- 자바
- 프로그래머스
- 이분탐색
- heapq
- 파이썬
- programmers
- java
- python
- 수학
Archives
- Today
- Total
상상쓰
[프로그래머스] [3차] 자동완성 본문
https://programmers.co.kr/learn/courses/30/lessons/17685
코딩테스트 연습 - [3차] 자동완성
자동완성 포털 다음에서 검색어 자동완성 기능을 넣고 싶은 라이언은 한 번 입력된 문자열을 학습해서 다음 입력 때 활용하고 싶어 졌다. 예를 들어, go 가 한 번 입력되었다면, 다음 사용자는 g
programmers.co.kr
저번에 Trie 자료구조를 유튜브를 통해서 배운 적이 있는데 문제를 보고 Trie 를 이용해야겠다고 생각이 났다.
문자열을 한 문자씩 정의하여 dictionary 에 담아서 dictionary[] 의 길이를 가지고 몇 번의 입력으로 자동완성이 되는지를 판별해주면 된다.
예를 들어, dictionary['g'] 의 길이가 2개 이상이라면 'g' 를 입력했을 때 2개의 단어를 추천해주므로 자동완성을 할 수 가 없다. 또한 'go' 와 'gone' 에서 dictionary['g']['o'] 의 길이는 1이나 'go' 를 입력했을 때 'go', 'gone' 을 추천해주므로 단어가 끝날 때 '!' 를 추가하여 구분해준다.
class Trie:
dictionary = {}
def insert(self, string):
current_dic = self.dictionary
for i in string:
if i not in current_dic:
current_dic[i] = {}
current_dic = current_dic[i]
current_dic['!'] = '!'
def check(self, string):
current_dic = self.dictionary
count = 0
for i in string:
if len(current_dic[i]) == 1:
count += 1
else:
count = 0
current_dic = current_dic[i]
return len(string) if count == 0 else len(string) - count + 1
def solution(words):
answer = 0
T = Trie()
for i in words:
T.insert(i)
for i in words:
answer += T.check(i)
return answer
print(solution(['go', 'gone', 'guild'])) # 7
참고 : https://www.youtube.com/watch?v=7e1b70dTAd4
'Coding Test' 카테고리의 다른 글
[백준] 한조서열정리하고옴ㅋㅋ (0) | 2021.07.05 |
---|---|
[백준] 과제 (0) | 2021.07.02 |
[프로그래머스] 징검다리 (0) | 2021.07.02 |
[프로그래머스] 기능개발 (0) | 2021.07.01 |
[백준] 게임을 만든 동준이 (0) | 2021.07.01 |
Comments