LeetCode 剑指 Offer II 062. 实现前缀树

思路

  • 在前缀树的每一个节点中,需要存储多个子节点信息和当前节点是否是word的结尾。存储子节点可以使用HashMap来实现。
  • 在insert算法中,需要循环判断当前字符是否在前缀树中出现,如果出现则继续判断下一个字符,否则创建一个新节点并存储后继续判断下一个字符。在字符串最后一个字符的节点处设置为结尾。
  • 在search算法中,与insert算法思路一致,循环找字符串中的每一个字符,但是如果没找到下一个节点则直接没找到。在成功遍历完所有节点后,再判断最后的节点是否是结尾。
  • 在startWith算法中,与search算法思路一致,但是最后遍历完所有节点则证明找到了以某一prefix开头的前缀,直接返回已找到。

JAVA实现

class Trie {

    /** Initialize your data structure here. */
    class TrieNode{
    	// 判断是否是word的结尾
        private boolean isEnd; 
        // 存储子节点
        private HashMap<Character,TrieNode> map;
        public TrieNode(){
            isEnd=false;
            map=new HashMap<>();
        }
        public boolean getIsEnd(){
            return isEnd;
        }
        public void setIsEnd(boolean isEnd){
            this.isEnd=isEnd;
        }
        public TrieNode getTrieNode(char c){
            return map.get(c);
        }
        public void addTrieNode(char c,TrieNode trieNode){
            map.put(c, trieNode);
        }

    }
    private TrieNode root;
    public Trie() {
        root=new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode tmp=root;
        // 从根节点开始遍历
        for(int i = 0;i<word.length();i++){
            char c = word.charAt(i);
            TrieNode next=tmp.getTrieNode(c);
            // 如果没找到则新创建一个节点
            if(next==null){
                next=new TrieNode();
                tmp.addTrieNode(c,next);
            }
            tmp=next;
        }
        // 遍历结束,设置当前字符为结尾
        tmp.setIsEnd(true);
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode tmp=root;
        for(int i = 0;i<word.length();i++){
            char c = word.charAt(i);
            TrieNode next=tmp.getTrieNode(c);
            // 如果子节点不存在则未找到
            if(next==null){
                return false;
            }
            tmp=next;
        }
        // 虽然成功遍历完所有字符,但还要看看是否是word结尾
        return tmp.getIsEnd();
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode tmp=root;
        for(int i = 0;i<prefix.length();i++){
            char c = prefix.charAt(i);
            TrieNode next=tmp.getTrieNode(c);
            if(next==null){
                return false;
            }
            tmp=next;
        }
        // 成功遍历完所有prefix字符
        return true;
    }
}

/**
 * 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、付费专栏及课程。

余额充值