Re: [闲聊] 每日leetcode

楼主: dont   2024-10-25 19:14:44
1233. Remove Sub-Folders from the Filesystem
## 思路
把folder都丢到Trie tree 并记录是否为目录尾 (is_end)
扫Trie tree时检查is_end
## Code
```python
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class TrieTree:
def __init__(self):
self.root = TrieNode()
def insert(self, path):
curr = self.root
for sub in path.split('/')[1:]:
if curr.is_end:
return
if sub not in curr.children:
curr.children[sub] = TrieNode()
curr = curr.children[sub]
curr.is_end = True
def get_all(self):
res = []
path = ['']
def recur(curr):
if curr.is_end:
res.append('/'.join(path))
return
for sub in curr.children:
path.append(sub)
recur(curr.children[sub])
path.pop()
recur(self.root)
return res
class Solution:
def removeSubfolders(self, folder: List[str]) -> List[str]:
trie = TrieTree()
for path in folder:
trie.insert(path)
return trie.get_all()
```

Links booklink

Contact Us: admin [ a t ] ucptt.com