디자인 추가 및 검색 단어
'디자인 추가 및 검색 단어' 문제에 대한 자세한 가이드 및 Python 구현입니다.
1. 배우다
'디자인 추가 및 검색 단어' 문제는 Trie 섹션의 핵심 과제입니다.
이 구현은 Python의 쉬운 수준 논리에 중점을 둡니다.
우리는 제공되는 솔루션에서 기술적 정확성과 코드 가독성을 최우선으로 생각합니다.
2. Real-World Applications
3. Visual Intuition
디자인 추가 및 검색 단어에 대한 논리 흐름을 시각화합니다.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
디자인 추가 및 검색 단어에 대한 문제 설명을 주의 깊게 읽으십시오.
2. Formulate brute force
간단한 반복 솔루션 초안을 작성합니다.
3. Identify inefficiency
중복 계산을 찾으십시오.
4. Optimize search path
해싱이나 정렬을 사용하여 프로세스 속도를 높입니다.
5. Final Implementation
생산 표준에 맞게 코드를 정리합니다.
문제 설명
새로운 단어를 추가하고 문자열이 이전에 추가된 문자열과 일치하는지 찾는 것을 지원하는 데이터 구조를 설계합니다.
WordDictionary 클래스를 구현합니다.
- WordDictionary() 개체를 초기화합니다.
- addWord(word: str) 데이터 구조에 단어를 추가합니다. 나중에 일치시킬 수 있습니다.
- search(word: str) -> bool 데이터 구조에 word와 일치하는 문자열이 있으면 True를 반환하고 그렇지 않으면 False를 반환합니다. 단어에는 점 '.'이 포함될 수 있습니다. 여기서 점은 어떤 문자와도 일치할 수 있습니다.
입력은 작업 및 인수 목록입니다. 결과 목록을 반환하는 wordDictionary(operations: list, arguments: list) -> list 함수를 구현합니다(생성자/addWord의 경우 없음, 검색의 경우 bool).
- •1 <= len(word) <= 25
- •word in addWord consists of lowercase English letters
- •word in search consists of '.' or lowercase English letters
- •At most 10^4 calls will be made to addWord and search
예
operations = ["WordDictionary", "addWord", "addWord", "addWord", "search", "search", "search", "search"], arguments = [[], ["bad"], ["dad"], ["mad"], ["pad"], ["bad"], [".ad"], ["b.."]]
[None, None, None, None, False, True, True, True]
Initialize. Add "bad", "dad", "mad". search("pad") -> False. search("bad") -> True. search(".ad") -> True. search("b..") -> 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 WordDictionaryOpt:
def __init__(self):
self.root = TrieNode()
def addWord(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):
def dfs(j, root):
curr = root
for i in range(j, len(word)):
c = word[i]
if c == ".":
for child in curr.children.values():
if dfs(i + 1, child): return True
return False
else:
if c not in curr.children: return False
curr = curr.children[c]
return curr.end
return dfs(0, self.root)무차별 대입 코드(스포일러 보호)
무차별 대입 코드(스포일러 보호)
class WordDictionaryBrute:
def __init__(self):
self.words = set()
def addWord(self, word):
self.words.add(word)
def search(self, word):
if '.' not in word: return word in self.words
for w in self.words:
if len(w) == len(word):
match = True
for i in range(len(word)):
if word[i] != '.' and word[i] != w[i]:
match = False; break
if match: 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 Try/Except 및 오류 처리
Python 스크립트가 충돌하는 것을 방지하세요. try, Except, finally 블록과 사용자 정의 예외를 올바르게 발생시키는 방법을 알아보세요.
Python에서 난수를 생성하는 방법(random 모듈)
Python에서 난수를 생성하는 방법을 알아보세요. randrange, randint 및 균일 부동 소수점 생성을 시딩 제어와 비교합니다.
Python pip 패키지 관리자 치트 시트
pip에 대한 명령줄 참조 가이드입니다. Python 패키지 및 종속성을 설치, 업그레이드, 제거 및 관리하는 방법을 알아보세요.
Python 대 JavaScript: 어떤 프로그래밍 언어가 가장 좋나요?
Python과 JavaScript를 포괄적으로 비교합니다. 구문 차이점, 성능, 사용 사례(백엔드와 프런트엔드) 및 코딩 예제를 살펴보세요.