字典树(前缀数)例题以及模板

字典树(前缀数)例题以及模板

先放题目

  1. leetcode 208 -基础字典树
    https://leetcode.com/problems/implement-trie-prefix-tree/
  2. leetcode 211-字典树模糊匹配
    https://leetcode.com/problems/add-and-search-word-data-structure-design/description/
  3. leetcode 212-二维数值字典树(bfs)
    https://leetcode.com/problems/word-search-ii/description/

解析

网上字典树的原理和解析很多,就不做太多分析和讲解了,直接上题简易模板。题型变化基于模板修改就可以。

  1. 字典树的结构

class TrieNode {
    public char val;
    public boolean isWord; 
    public TrieNode[] children = new TrieNode[26];
    public TrieNode() {}
    TrieNode(char c){
        TrieNode node = new TrieNode();
        node.val = c;
    }
}
  • 添加 insert(aabccc)

  public void insert(String word) {
        TrieNode ws = root;
        for(int i = 0; i < word.length(); i++){
            char c = word.charAt(i);
            if(ws.children[c - 'a'] == null){
                ws.children[c - 'a'] = new TrieNode(c);
            }
            ws = ws.children[c - 'a'];
        }
        ws.isWord = true;
    }
  • 全匹配搜索 search(aabccc)->true

 public boolean search(String word) {
        TrieNode ws = root; 
        for(int i = 0; i < word.length(); i++){
            char c = word.charAt(i);
            if(ws.children[c - 'a'] == null) return false;
            ws = ws.children[c - 'a'];
        }
        return ws.isWord;
    }
  • 前缀搜索 startsWith(aabc)->true

 public boolean startsWith(String prefix) {
        TrieNode ws = root; 
        for(int i = 0; i < prefix.length(); i++){
            char c = prefix.charAt(i);
            if(ws.children[c - 'a'] == null) return false;
            ws = ws.children[c - 'a'];
        }
        return true;
    }
  • 模糊匹配 fuzzySearch(.abc..)->true

    public boolean fuzzySearch(String word) {
        return search(word.toCharArray(), 0, root);                  
    }
    
    private boolean fuzzySearch(char[] chars, int index, TrieNode parent){
        if (index == chars.length){
            if (parent.isLeaf){
                return true;
            }
            return false;
        }
        TrieNode [] childNodes = parent.children;
        char c = chars[index];
        if (c == '.'){
            for (int i=0;i<childNodes.length;i++){
                TrieNode n = childNodes[i];
                if (n !=null){
                    boolean b = fuzzySearch(chars, index+1, n);
                    if (b){
                        return true;
                    }
                }
            }
            return false;
        }
        TrieNode node = childNodes[c-'a'];
        if (node == null){
            return false;
        }
        return search(chars, ++index, node);
    }
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值