LintCode:实现 Trie

116 篇文章 0 订阅
27 篇文章 0 订阅

LintCode:实现 Trie

参考地址:百度百科–字典树

Python

"""
Your Trie object will be instantiated and called as such:
trie = Trie()
trie.insert("lintcode")
trie.search("lint") will return false
trie.startsWith("lint") will return true
"""
class TrieNode:
    def __init__(self):
    # Initialize your data structure here.
        self.val = 0
        self.is_word = False
        self.childs = [None for i in range(26)]

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

  # @param {string} word
  # @return {void}
  # Inserts a word into the trie.
    def insert(self, word):
        if not word or len(word) == 0:
            return
        my_root = self.root
        for ch in word:
            if not my_root.childs[ord(ch) - ord('a')]:
                my_root.childs[ord(ch) - ord('a')] = TrieNode()
                my_root.childs[ord(ch) - ord('a')].val = ch
                my_root = my_root.childs[ord(ch) - ord('a')]
            else:
                my_root = my_root.childs[ord(ch) - ord('a')]


        my_root.is_word = True


  # @param {string} word
  # @return {boolean}
  # Returns if the word is in the trie.
    def search(self, word):
        my_root = self.root
        for ch in word:
            if not my_root.childs[ord(ch) - ord('a')] or ch != my_root.childs[ord(ch) - ord('a')].val:
                return False
            my_root = my_root.childs[ord(ch) - ord('a')]
        return my_root.is_word

  # @param {string} prefix
  # @return {boolean}
  # Returns if there is any word in the trie
  # that starts with the given prefix.
    def startsWith(self, prefix):
        my_root = self.root
        for ch in prefix:
            if not my_root.childs[ord(ch) - ord('a')] or ch != my_root.childs[ord(ch) - ord('a')].val:
                return False
            my_root = my_root.childs[ord(ch) - ord('a')]
        return True

Java

/**
 * Your Trie object will be instantiated and called as such:
 * Trie trie = new Trie();
 * trie.insert("lintcode");
 * trie.search("lint"); will return false
 * trie.startsWith("lint"); will return true
 */
class TrieNode {
    // Initialize your data structure here.
    public boolean isWord;
    public char val;
    public TrieNode[] son;
    public TrieNode() {
        son = new TrieNode[26];
        isWord = false;
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        if(word == null || word.length() == 0){
            return;
        }
        TrieNode node = root;
        char[] letters = word.toCharArray();
        for(int i=0; i<word.length(); i++){
            int pos = letters[i] - 'a';
            if(node.son[pos] == null){
                node.son[pos] = new TrieNode();
                node.son[pos].val = letters[i];
            }
            node = node.son[pos];
        }
        node.isWord = true;

    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        if(word == null || word.length() == 0){
            return false;
        }
        TrieNode node = root;
        char[] letters = word.toCharArray();
        for(int i=0; i<word.length(); i++){
            int pos = letters[i] - 'a';
            if(node.son[pos] != null){
                node = node.son[pos];
            }
            else{
                return false;
            }
        }
        return node.isWord;

    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        if(prefix == null || prefix.length() == 0){
            return false;
        }
        TrieNode node = root;
        char[] letters = prefix.toCharArray();
        int i = 0;
        for(; i<prefix.length(); i++){
            int pos = letters[i] - 'a';
            if(node.son[pos] != null){
                node = node.son[pos];
            }
            else{
                return false;
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值