Trie 접두사 트리 구현
'Implement Trie Prefix Tree' 문제에 대한 자세한 가이드 및 Python 구현입니다.
1. 배우다
'Implement Trie Prefix Tree' 문제는 Trie 섹션의 핵심 과제입니다.
이 구현은 Python의 중간 수준 논리에 중점을 둡니다.
우리는 제공되는 솔루션에서 기술적 정확성과 코드 가독성을 최우선으로 생각합니다.
2. Real-World Applications
3. Visual Intuition
Trie 접두사 트리 구현에 대한 논리 흐름을 시각화합니다.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Trie Prefix Tree 구현에 대한 문제 설명을 주의 깊게 읽어보세요.
2. Formulate brute force
간단한 반복 솔루션 초안을 작성합니다.
3. Identify inefficiency
중복 계산을 찾으십시오.
4. Optimize search path
해싱이나 정렬을 사용하여 프로세스 속도를 높입니다.
5. Final Implementation
생산 표준에 맞게 코드를 정리합니다.
문제 설명
트리('try'로 발음) 또는 접두사 트리는 문자열 데이터세트에서 키를 효율적으로 저장하고 검색하는 데 사용되는 트리 데이터 구조입니다. 자동 완성 및 맞춤법 검사기와 같은 이 데이터 구조의 다양한 응용 프로그램이 있습니다.
Trie 클래스를 구현합니다.
- Trie() trie 객체를 초기화합니다.
- insert(word: str) 문자열 word를 트라이에 삽입합니다.
- search(word: str) -> bool 문자열 단어가 트리에 있으면(즉, 이전에 삽입된 경우) True를 반환하고 그렇지 않으면 False를 반환합니다.
- startWith(prefix: str) -> bool 접두사 접두사가 있는 이전에 삽입된 문자열 단어가 있으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.
입력은 작업 및 인수 목록입니다. 결과 목록을 반환하는 trie(operations: list, arguments: list) -> list 함수를 구현합니다(생성자/삽입의 경우 None, 검색/startsWith의 경우 bool).
- •1 <= len(word), len(prefix) <= 2000
- •word and prefix consist of lowercase English letters
- •At most 3 * 10^4 calls will be made in total to insert, search, and startsWith
예
operations = ["Trie", "insert", "search", "search", "startsWith", "insert", "search"], arguments = [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
[None, None, True, False, True, None, True]
Trie initialized. insert("apple"). search("apple") returns True. search("app") returns False. startsWith("app") returns True. insert("app"). search("app") returns True.
Need a Hint?
Edge Cases to Watch
- 빈 입력 구조
- 단일 요소 입력
- 큰 수치 범위
해결할 준비가 되셨나요?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
인터뷰 통찰력 및 변형
복잡성 분석 분석
왜 시간인가?: Directly evaluates all possibilities.
왜 우주인가?: Uses standard local memory.
왜 시간인가?: Optimized paths reduce total operations.
왜 우주인가?: May trade memory for speed.
최적화된 솔루션 Python 코드
최적화된 솔루션 Python 코드
class TrieNode:
def __init__(self):
self.children = {}
self.end = False
class TrieOpt:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
curr = self.root
for c in word:
if c not in curr.children: curr.children[c] = TrieNode()
curr = curr.children[c]
curr.end = True
def search(self, word):
curr = self.root
for c in word:
if c not in curr.children: return False
curr = curr.children[c]
return curr.end
def startsWith(self, prefix):
curr = self.root
for c in prefix:
if c not in curr.children: return False
curr = curr.children[c]
return True무차별 대입 코드(스포일러 보호)
무차별 대입 코드(스포일러 보호)
class TrieBrute:
def __init__(self):
self.words = set()
def insert(self, word):
self.words.add(word)
def search(self, word):
return word in self.words
def startsWith(self, prefix):
for w in self.words:
if w.startswith(prefix): return True
return FalseAlgorithm Pattern Checklist
When dealing with Trie data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
표준 트라이 문제 속성이 적용됩니다.
관련 질문
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
권장 Python 리소스
관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.
Python 루프
Python 루프를 사용하여 데이터를 반복하는 방법을 알아보세요. 대화형 예제를 통해 for 루프, while 루프, 중단, 계속 및 루프 모범 사례를 마스터하세요.
Python에서 목록을 정렬하는 방법(오름차순 및 내림차순)
sort() 메서드와 sorted() 함수를 사용하여 Python에서 목록을 정렬하는 방법을 알아보세요. 사용자 정의 키 정렬 및 역순 예시를 살펴보세요.
Python 문자열 메서드 치트 시트
Python 문자열 조작에 대한 완전한 참조 가이드입니다. 문자열 속성의 서식 지정, 검색, 분할, 바꾸기 및 확인을 마스터합니다.
Python 대 JavaScript: 어떤 프로그래밍 언어가 가장 좋나요?
Python과 JavaScript를 포괄적으로 비교합니다. 구문 차이점, 성능, 사용 사례(백엔드와 프런트엔드) 및 코딩 예제를 살펴보세요.