mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 14:56:27 -04:00
add trie class
This commit is contained in:
parent
05ffc6e0b7
commit
39262bfbe4
1 changed files with 31 additions and 0 deletions
|
@ -18,6 +18,37 @@
|
|||
|
||||
<br>
|
||||
|
||||
```python
|
||||
class Trie:
|
||||
|
||||
def __init__(self):
|
||||
self.root = {}
|
||||
|
||||
def insert(self, word: str) -> None:
|
||||
node = self.root
|
||||
for c in word:
|
||||
if c not in node:
|
||||
node[c] = {}
|
||||
node = node[c]
|
||||
node['$'] = None
|
||||
|
||||
def match(self, seq, prefix=False):
|
||||
node = self.root
|
||||
for c in seq:
|
||||
if c not in node:
|
||||
return False
|
||||
node = node[c]
|
||||
return prefix or ('$' in node)
|
||||
|
||||
def search(self, word: str) -> bool:
|
||||
return self.match(word)
|
||||
|
||||
def startsWith(self, prefix: str) -> bool:
|
||||
return self.match(prefix, True)
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
----
|
||||
|
||||
### insertion
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue