1+ class Trie :
2+
3+ def __init__ (self ):
4+ self .children = {}
5+ self .is_end = False
6+
7+ def insert (self , word : str ) -> None :
8+ node = self
9+ for c in word :
10+ if c not in node .children :
11+ node .children [c ] = Trie ()
12+ node = node .children [c ]
13+ node .is_end = True
14+
15+ def search (self , word : str ) -> bool :
16+ node = self ._find (word )
17+ return node is not None and node .is_end
18+
19+ def startsWith (self , prefix : str ) -> bool :
20+ return self ._find (prefix ) is not None
21+
22+ def _find (self , s : str ):
23+ node = self
24+ for c in s :
25+ if c not in node .children :
26+ return None
27+ node = node .children [c ]
28+ return node
29+
30+
31+ """
32+ ================================================================================
33+ 풀이 과정
34+ ================================================================================
35+
36+ [문제 이해]
37+ ────────────────────────────────────────────────────────────────────────────────
38+ 1. Trie(트라이) 자료구조 구현
39+ 2. insert(word): 단어 삽입
40+ 3. search(word): 정확히 일치하는 단어 있는지
41+ 4. startsWith(prefix): prefix로 시작하는 단어 있는지
42+
43+
44+ [1차 시도] 해시맵
45+ ────────────────────────────────────────────────────────────────────────────────
46+ 5. 처음에 해싱으로 풀었더니 통과는 했는데 startsWith에서 결국 전체 순회 필요
47+ 6. 시간복잡도 O(n × m) → 비효율적, 진짜 Trie로 풀어야겠다
48+
49+
50+ [2차 시도] 진짜 Trie
51+ ────────────────────────────────────────────────────────────────────────────────
52+ 7. 각 노드가 children(자식 노드들)과 is_end(단어 끝 여부)를 가짐
53+
54+ 8. 구조 예시: "app", "apple" 삽입 시
55+
56+ root
57+ │
58+ a
59+ │
60+ p
61+ │
62+ p (is_end: "app")
63+ │
64+ l
65+ │
66+ e (is_end: "apple")
67+
68+ 9. insert: 문자 하나씩 따라가며 노드 생성, 마지막에 is_end = True
69+ 10. search: 문자 따라간 후 is_end가 True인지 확인
70+ 11. startsWith: 문자 따라갈 수 있으면 True
71+
72+
73+ [복잡도 분석]
74+ ────────────────────────────────────────────────────────────────────────────────
75+ 12. 시간복잡도: O(m) - 모든 연산
76+ - m: 단어/prefix 길이
77+
78+ 13. 공간복잡도: O(n × m)
79+ - n: 단어 개수, m: 평균 단어 길이
80+ """
0 commit comments