-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path2416-sum-of-prefix-scores-of-strings.py
More file actions
44 lines (34 loc) · 1.06 KB
/
2416-sum-of-prefix-scores-of-strings.py
File metadata and controls
44 lines (34 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# time complexity: O(n*m)
# space complexity: O(n*m)
from typing import List
class trie_node:
def __init__(self):
self.next = [None] * 26
self.cnt = 0
class Solution:
def __init__(self):
self.root = trie_node()
def insert(self, word):
node = self.root
for c in word:
if node.next[ord(c) - ord("a")] is None:
node.next[ord(c) - ord("a")] = trie_node()
node.next[ord(c) - ord("a")].cnt += 1
node = node.next[ord(c) - ord("a")]
def count(self, s):
node = self.root
ans = 0
for c in s:
ans += node.next[ord(c) - ord("a")].cnt
node = node.next[ord(c) - ord("a")]
return ans
def sumPrefixScores(self, words: List[str]) -> List[int]:
N = len(words)
for i in range(N):
self.insert(words[i])
scores = [0] * N
for i in range(N):
scores[i] = self.count(words[i])
return scores
words = ["abc", "ab", "bc", "b"]
print(Solution().sumPrefixScores(words))