ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค / 2018 KAKAO ์ž๋™์™„์„ฑ / ํŒŒ์ด์ฌ / ํŠธ๋ผ์ด
Problem Solving ๐Ÿ”ฅ/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค / 2018 KAKAO ์ž๋™์™„์„ฑ / ํŒŒ์ด์ฌ / ํŠธ๋ผ์ด

programmers.co.kr/learn/courses/30/lessons/17685

Trie ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์•ˆ๋‹ค๋ฉด ์‰ฌ์šด ๋ฌธ์ œ์ด๊ณ  ๋ชจ๋ฅด๋ฉด ์–ด๋ ค์šด ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

Trie ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์กฐ๊ธˆ ๋ณ€ํ˜•ํ•˜์—ฌ ์‰ฝ๊ฒŒ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค.
Trie์— cnt๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

cnt๋Š” ๊ฐ™์€ ๋ฃจํŠธ๋ฅผ ๊ณต์œ ํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.
cnt๊ฐ€ 1์ด๋ผ๋ฉด ๋” ์ด์ƒ ์ฐพ์•„๋ณผ ์ด์œ ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.

๊ทธ๋ฆฌ๊ณ  cnt๋Š” ๋ฌธ์ž์—ด ๊ธธ์ด๋ฅผ ๋„˜์„ ์ˆ˜ ์—†์Œ์— ์œ ์˜ํ•ฉ๋‹ˆ๋‹ค.

class Trie:
    def __init__(self):
        self.root = Node()

    def insert(self, s):
        node = self.root
        for c in s:
            if c in node.child:
                node.child[c].cnt += 1
            else:
                node.child[c] = Node()
            node = node.child[c]
        node.child['*'] = Node()

    def search(self, s):
        node = self.root
        cnt = 1
        for c in s:
            node = node.child[c]
            if node.cnt == 1:
                return cnt
            cnt += 1
        return min(cnt, len(s))

class Node:
    def __init__(self):
        self.child = {}
        self.cnt = 1

def solution(words):
    answer = 0
    root = Trie()
    for word in words:
        root.insert(word)
    for word in words:
        answer += root.search(word)
    return answer