ps | |
---|---|
링크 | programmers.co.kr/… |
출처 | 프로그래머스 |
문제 번호 | 60060 |
문제명 | 가사 검색 |
레벨 | Level 4 |
분류 |
트라이 |
시간복잡도 | O(w+q) |
인풋사이즈 | w<=1,000,000, q<=1,000,000 |
사용한 언어 | Python |
해결날짜 | 2021/01/04 |
"""Solution code for "Programmers 60060. 가사 검색".
- Problem link: https://programmers.co.kr/learn/courses/30/lessons/60060
- Solution link: http://www.teferi.net/ps/problems/programmers/60060
"""
from teflib import string
MAX_LEN = 10000
def solution(words, queries):
tries = [string.Trie() for _ in range(MAX_LEN + 1)]
rev_tries = [string.Trie() for _ in range(MAX_LEN + 1)]
for word in words:
tries[len(word)].add(word)
rev_tries[len(word)].add(reversed(word))
answer = []
for query in queries:
try:
if query[0] == '?':
node = rev_tries[len(query)][reversed(query.lstrip('?'))]
answer.append(rev_tries[len(query)].get_child_count(node))
else:
node = tries[len(query)][query.rstrip('?')]
answer.append(tries[len(query)].get_child_count(node))
except KeyError:
answer.append(0)
return answer