forked from das-jishu/algoexpert-data-structures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspecial-strings.py
43 lines (33 loc) · 983 Bytes
/
special-strings.py
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
# SPECIAL STRINGS
def specialStrings(strings):
# Write your code here.
trie = Trie()
for string in strings:
trie.buildTrie(string)
specials = []
for string in strings:
if checkSpecial(string, trie.root, 0, 0, trie):
specials.append(string)
return specials
def checkSpecial(string, node, index, count, trie):
letter = string[index]
if letter not in node:
return False
if index == len(string) - 1:
return trie.endSymbol in node[letter] and count > 0
if trie.endSymbol in node[letter]:
remainingSpecial = checkSpecial(string, trie.root, index + 1, count + 1, trie)
if remainingSpecial:
return True
return checkSpecial(string, node[letter], index + 1, count, trie)
class Trie:
def __init__(self):
self.root = {}
self.endSymbol = "*"
def buildTrie(self, string):
current = self.root
for letter in string:
if letter not in current:
current[letter] = {}
current = current[letter]
current[self.endSymbol] = True