Re: [闲聊] 每日leetcode

楼主: dont   2024-09-25 10:09:34
2416. Sum of Prefix Scores of Strings
## 思路
跟前几天一样是TrieTree
把Word加进Trie时 每个prefix的count都+1
最后再扫Trie得到prefix score总和
## Code
```python
class TrieNode:
def __init__(self):
self.children = {}
self.count = 0
class TrieTree:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
curr = self.root
for ch in word:
if ch not in curr.children:
curr.children[ch] = TrieNode()
curr = curr.children[ch]
curr.count += 1
def search(self, word):
res = 0
curr = self.root
for ch in word:
curr = curr.children[ch]
res += curr.count
return res
class Solution:
def sumPrefixScores(self, words: List[str]) -> List[int]:
trie = TrieTree()
for word in words:
trie.insert(word)
return [trie.search(word) for word in words]
```

Links booklink

Contact Us: admin [ a t ] ucptt.com