Leetcode 208、实现Trie(前缀树)

Leetcode 208、实现Trie(前缀树)

在这里插入图片描述

使用数组实现前缀树

  • insert()

    向前缀树里面插入字符串
    遍历当前要插入的字符串,查看当前数组对应的位置是否为空

    如果为空,temp[curr] = new Trie();并且temp = temp[curr].children;
    就是继续向下添加;如果当前位置是字符串的最后一个位置,那么对应的Trie
    里面的endWith = true;

    如果不为空,就直接temp = temp[curr].children,并且如果一直都不为空,
    那么遍历到最后一个字符的时候,需要把对应的endWith设置为true,
    即:temp[curr].endWith = true;

  • search()
    遍历当前要查找的字符串,如果当前位置为空,直接返回false;
    如果不为空,继续向下遍历前缀树;如果当前是字符串的最后
    一个字符,判断当前temp[curr].endWith是否为true,不是的话返回false。

  • startsWith()

    这里查询的是前缀,所以不需要判断endWith
    遍历要查找的prefix,如果Trie当前位置为空,返回false;
    不为空继续向下遍历字符串和Trie。

class Trie {
    Trie[] children;
    boolean endWith;
    public Trie() {
        children = new Trie[26];
        endWith = false;
    }
	
	/**
		向前缀树里面插入字符串
		遍历当前要插入的字符串,查看当前数组对应的位置是否为空
		
		如果为空,temp[curr] = new Trie();并且temp = temp[curr].children;
		就是继续向下添加;如果当前位置是字符串的最后一个位置,那么对应的Trie
		里面的endWith = true;
		
		如果不为空,就直接temp = temp[curr].children,并且如果一直都不为空,
		那么遍历到最后一个字符的时候,需要把对应的endWith设置为true,
		即:temp[curr].endWith = true;
	**/
    public void insert(String word) {
        Trie[] temp = children;
        for(int i = 0; i < word.length(); i++) {
            int curr = word.charAt(i) - 'a';
            if(temp[curr] == null) {
                temp[curr] = new Trie();
                if(i == word.length() - 1) {
                    temp[curr].endWith = true;
                }
                temp = temp[curr].children;
            }else{
                if(i == word.length() - 1) {
                    temp[curr].endWith = true;
                }
                temp = temp[curr].children;
            }
        }
    }
	
	/**
		遍历当前要查找的字符串,如果当前位置为空,直接返回false;
		如果不为空,继续向下遍历前缀树;如果当前是字符串的最后
		一个字符,判断当前temp[curr].endWith是否为true,不是的
		话返回false。
	**/
    public boolean search(String word) {
        Trie[] temp = children;
        for(int i = 0; i < word.length(); i++) {
            int curr = word.charAt(i) - 'a';
            if(temp[curr] != null) {
                if(i == word.length() - 1 && temp[curr].endWith) {
                    return true;
                }
                temp = temp[curr].children;

            }else if(i != word.length() - 1 && temp[curr] == null) {
                return false;
            }
        }
        return false;
    }
	
	/**
		这里查询的是前缀,所以不需要判断endWith
		遍历要查找的prefix,如果Trie当前位置为空,返回false;
		不为空继续向下遍历字符串和Trie。
	**/
    public boolean startsWith(String prefix) {
        Trie[] temp = children;
        for(int i = 0; i < prefix.length(); i++) {
            int curr = prefix.charAt(i) - 'a';
            if(temp[curr] != null) {
                if(i == prefix.length() - 1) {
                    return true;
                }
                temp = temp[curr].children;
            }else if(i != prefix.length() - 1 && temp[curr] == null) {
                return false;
            }
        }
        return false;
    }
}
### 实现 Trie前缀) 为了实现 Trie 数据结构,在 Java 中可以定义一个 `TrieNode` 类来表示节点,并创建相应的操作方法。下面是一个完整的解决方案: #### 定义 Trie 节点 每个节点包含指向其子节点的链接列表以及是否为单词结束标志。 ```java class TrieNode { private final int R = 26; private TrieNode[] links; private boolean isEnd; public TrieNode() { links = new TrieNode[R]; } // 判断是否存在字符对应的子节点 public boolean containsKey(char ch) { return links[ch - 'a'] != null; } // 获取指定字符对应的孩子结点 public TrieNode get(char ch) { return links[ch - 'a']; } // 设置当前结点孩子结点 public void put(char ch, TrieNode node) { links[ch - 'a'] = node; } // 标记该位置是否有字符串终止于此处 public void setEnd() { isEnd = true; } // 是否有字符串在此终结 public boolean isEnd() { return isEnd; } } ``` #### 创建 Trie 类并提供接口函数 通过封装上述基本功能,可构建更高级别的 API 来支持插入、搜索和查询以特定前缀开头的所有键等功能。 ```java class Trie { private final TrieNode root; /** Initialize your data structure here. */ public Trie() { root = new TrieNode(); } /** Inserts a word into the trie. */ public void insert(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { char currentChar = word.charAt(i); if (!node.containsKey(currentChar)) { node.put(currentChar, new TrieNode()); } node = node.get(currentChar); } node.setEnd(); } /** Returns if the word is in the trie. */ public boolean search(String word) { TrieNode node = searchPrefix(word); return node != null && node.isEnd(); } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { TrieNode node = searchPrefix(prefix); return node != null; } private TrieNode searchPrefix(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { char curLetter = word.charAt(i); if (node.containsKey(curLetter)) { node = node.get(curLetter); } else { return null; } } return node; } } /** * 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); */ ``` 此代码实现Trie 的核心逻辑,包括初始化、插入新词、查找完整匹配项以及检查给定前缀的存在性[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值