목차

가사 검색

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