leetcode 208 trie字典树 -- python+java实现

1. python

1.1 collections.defaultdict(valueType)的使用

defaultdict means that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.

For example:

somedict = {}
print(somedict[3]) # KeyError

someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0

1.2 代码

'''
# collections.defaultdict字典,key是letter即代替了数组中index的作用,在Java中定义为数组,那么还需要indexForChar(letter)来将letter转化为index存入or访问数组index上的元素。value是TrieNode,即java中的Node()
'''
class TrieNode:
    def __init__(self):
        self.childs = collections.defaultdict(TrieNode) 
        self.is_word = False

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TrieNode()


    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        current = self.root
        for letter in word:
            current = current.childs[letter] # 如果不存在该key(letter),就创建一个entry(key-value pair)
        current.is_word = True


    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        current = self.root
        for letter in word:
            current = current.childs.get(letter, None) # 字典中存在这个letter吗?如果是,继续下一循环,如果否,返回false
            if current is None:
                return False
        return current.is_word


    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        current = self.root
        for letter in prefix:
            current = current.childs.get(letter, None)
            if current is None:
                return False
        return True
        


trie = Trie()

trie.insert("apple")
trie.search("apple")   
trie.search("app")     
trie.startsWith("app") 
trie.insert("app")   
trie.search("app")  


# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

2. JAVA

使用递归实现insert,search,startsWith

代码

class Trie {
    private class Node {
        Node[] childs = new Node[26];
        boolean isLeaf;
    }
    private Node root = new Node();
    /** Initialize your data structure here. */
    public Trie() {

    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        insert(word, root);
    }
    private void insert(String word, Node root){
        if (root == null) return;
        if (word.length() == 0) {
            root.isLeaf = true;
            return;
        }
        int index = indexForChar(word.charAt(0));//word第一个字符的字符编号(在Node[] childs中的index)
        if (root.childs[index] == null) root.childs[index] = new Node();//如node不存在,新建node
        insert(word.substring(1), root.childs[index]);
    }
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        return search(word, root);

    }
    private boolean search(String word, Node root){
        if (root == null) return false; //找不到,返回false
        if (word.length() == 0) return root.isLeaf; //这个单词存不存在在trie中,取决于最后一个字符的isLeaf属性
        int index = indexForChar(word.charAt(0));
        return search(word.substring(1), root.childs[index]);
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        return startsWith(prefix, root);

    }
    private boolean startsWith(String prefix, Node root){
        if (root == null) return false; //找不到,返回false
        if (prefix.length() == 0) return true;
        int index = indexForChar(prefix.charAt(0));
        return startsWith(prefix.substring(1), root.childs[index]);
    }
    private int indexForChar(char c){
        return c - 'a';
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值