Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Method 1:
- '''
- class Trie:
- def __init__(self):
- self.root={}
- def insert(self, word: str) -> None:
- cur=self.root
- for char in word:
- cur=cur.setdefault(char,{})
- cur['*']=True
- def search(self, word: str) -> bool:
- cur=self.root
- for char in word:
- if char not in cur:
- return False
- else:
- cur=cur[char]
- if '*' in cur:
- return True
- else:
- return False
- def startsWith(self, pref: str) -> bool:
- cur=self.root
- for char in pref:
- if char not in cur:
- return False
- cur=cur[char]
- return True
- '''
- Method 2:
- '''
- class Trie:
- def __init__(self):
- self.root={}
- def insert(self, word: str) -> None:
- cur=self.root
- for char in word:
- if char in cur:
- cur=cur[char]
- else:
- cur[char]={}
- cur=cur[char]
- cur['*']=True
- def search(self, word: str) -> bool:
- cur=self.root
- for char in word:
- if char not in cur:
- return False
- else:
- cur=cur[char]
- if '*' in cur:
- return True
- else:
- return False
- def startsWith(self, pref: str) -> bool:
- cur=self.root
- for char in pref:
- if char not in cur:
- return False
- cur=cur[char]
- return True
Add Comment
Please, Sign In to add comment