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
'Problem Solving ๐ฅ > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] ๋ฌด์ง์ ๋จน๋ฐฉ ๋ผ์ด๋ธ / ์ฐ์ ์์ ํ(ํ) (0) | 2021.05.03 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค] ๋งค์ถ ํ๋ฝ ์ต์ํ / ํ์ด์ฌ / DP (0) | 2021.05.02 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์คํจ์จ / Python (0) | 2021.04.07 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์์ ๊ฒ์ / Python (0) | 2021.04.06 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์ฟ ํค ๊ตฌ์ / ํ์ด์ฌ (0) | 2021.02.22 |