Implement Trie ii

Example:
Input:
1
6
insert samsung
insert samsung
insert vivo
erase vivo
countWordsEqualTo samsung
countWordsStartingWith vi
Output:
2
0
Explanation: Insert “samsung”: we are going to insert the word “samsung” into the “TRIE”.
Insert “samsung”: we are going to insert the word “samsung” again into the “TRIE”.
Insert “vivo”: we are going to insert the word “vivo” into the “TRIE”.
Erase “vivo”: we are going to delete the word “vivo” from the “TRIE”.
countWordsEqualTo “samsung”: There are two instances of “samsung” is present in “TRIE”.
countWordsStartWith “vi”:There is not a single word in the “TRIE” that starts from the prefix “vi”.
class Node:
def __init__(self):
self.arr = [None for i in range(26)]
self.prefix=0
self.flag=False

def contains(self,character):
if(self.arr[ord(character)-97]):
return True
def get(self,character):
return(self.arr[ord(character)-97])
def setEnd(self):
self.flag=True
def getEnd(self):
return self.flag==True
def put(self, character):
self.arr[ord(character)-97]=Node()


class Trie:
def __init__(self) :
self.root=Node()


def insert(self, string) :
temp = self.root
for i in string:
if not temp.contains(i):
temp.put(i)
temp=temp.get(i)
temp.prefix+=1
temp.setEnd()
def countWordsEqualTo(self, word):
temp = self.root
for i in word:
if not temp.contains(i):
return 0
temp=temp.get(i)
if temp.getEnd() :
return temp.prefix
def countWordsStartingWith(self, word):
temp = self.root
for i in word:
if not temp.contains(i):
return 0
temp=temp.get(i)
return temp.prefix
def erase(self, word):
temp = self.root
for i in word:
if temp.contains(i):
temp=temp.get(i)
temp.prefix-=1

--

--

--

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

That’s how we post

Agil lean methodology for new startups

Top 10 Tools for Easy Agile Project Management in 2021–2022

Contributing the Go Compiler: Adding New Tilde (~) Operator

Solved: When the Maven Deploy Plugin silently fails to deploy

If AppImage, Flatpak and Snap don’t cut it, you can roll your own

Navigating the cloud options for application deployment

Why Teams Adopting Kubernetes Fight over Capacity Management?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

More from Medium

Building a large-scale distributed storage system based on CNFS

Longest String with All Prefixes

Introduction to Node.js