File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Trienode :
2
+ def __init__ (self ):
3
+ self .ch = [None ]* 26
4
+ self .endofword = None
5
+ class Tries :
6
+ def __init__ (self ):
7
+ self .head = None
8
+ def findkey (self ,x ):
9
+ if ord (x )>= 97 and ord (x )<= 122 :
10
+ return ord (x )- 97
11
+ if ord (x )>= 65 and ord (x )<= 90 :
12
+ return ord (x )- 65
13
+
14
+ def add (self ,s ):
15
+ if self .head == None :
16
+ self .head = Trienode ()
17
+ tmp = self .head .ch
18
+ for i in range (len (s )):
19
+ key = self .findkey (s [i ])
20
+ if tmp [key ]== None :
21
+ tmp [key ]= Trienode ()
22
+ if i != len (s )- 1 :
23
+ tmp = tmp [key ].ch
24
+ else :
25
+ tmp [key ].endofword = '#'
26
+ def search (self ,s ):
27
+ if self .head == None :
28
+ print ("Not Found" )
29
+ else :
30
+ tmp = self .head .ch
31
+ for i in range (len (s )):
32
+ key = self .findkey (s [i ])
33
+ if tmp [key ]== None :
34
+ print ("Not found" )
35
+ return
36
+ else :
37
+ tempo = tmp
38
+ tmp = tmp [key ].ch
39
+ if tempo [key ].endofword == '#' :
40
+ print ("FOUND" )
41
+ else :
42
+ print ("Not Found" )
43
+ t = Tries ()
44
+ t .add ("apple" )
45
+ t .add ("ball" )
46
+ t .search ("apple" )
You can’t perform that action at this time.
0 commit comments