Share my AC python Solution


  • 0
    L

    One node after one node.

    class TrieNode:
    # Initialize your data structure here.
    def __init__(self):
    	self.val=None;
    	self.next={};
    	self.end=False; # some ends in this node?
    
    
    class Trie:
    
    def __init__(self):
    	self.root = TrieNode()
    
    # @param {string} word
    # @return {void}
    # Inserts a word into the trie.
    def insert(self, word):
    	p=self.root;
    	for c in word:
    		if(c not in p.next):
    			tn=TrieNode();
    			tn.val=c;
    			p.next[c]=tn;
    		p=p.next[c];
    	p.end=True;
    
    # @param {string} word
    # @return {boolean}
    # Returns if the word is in the trie.
    def search(self, word):
    	p=self.root;
    	for c in word:
    		if(c not in p.next):
    			return False;
    		p=p.next[c];
    	return p.end;
    	
    
    # @param {string} prefix
    # @return {boolean}
    # Returns if there is any word in the trie
    # that starts with the given prefix.
    def startsWith(self, prefix):
    	p=self.root;
    	for c in prefix:
    		if(c not in p.next):
    			return False;
    		p=p.next[c];
    	return True;

  • 0

    Looks like you don't really need the .val value...


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.