ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [3차] 자동완성
    코딩 테스트/Level 4 2022. 12. 4. 00:22
    반응형

    https://school.programmers.co.kr/learn/courses/30/lessons/17685

    class Node:
        def __init__(self):
            self.count = 0
            self.children = {}
    
    
    class Trie:
        def __init__(self):
            self.root = Node()
    
        def insert(self, word):
            current = self.root
            for letter in word:
                if letter not in current.children:
                    current.children[letter] = Node()
                current = current.children[letter]
                current.count += 1
    
        def search(self, word):
            current = self.root
            for index, letter in enumerate(word):
                current = current.children[letter]
                if current.count == 1:
                    return index + 1
            return len(word)
    
    
    def solution(words):
        trie = Trie()
        for word in words:
            trie.insert(word)
        return sum(trie.search(word) for word in words)
    반응형
Designed by Tistory.