Leetcode Trie前缀树相关题目解析以及java实现

Leetcode Trie前缀树相关题目解析以及java实现

Trie 其实还是一个挺实用得数据结构得,可以做到和哈希表一样得查找时间复杂度在leetcode里面虽然不常见但是也还是能遇到得,我们来看看和Trie 相关的两道题目,让我们更好得理解Trie得实现。

    1. Design Add and Search Words Data Structure
    1. Word Search II

Design Add and Search Words Data Structure

这一题要求我们设计一种数据结构,可以插入和查找相对应得字符串,一般看到这里就会想到用哈希表来做了,因为哈希表得查找速度是最快得,但是这里有一些不同要求我们可以利用.来代表任意字符,所以利用Trie来说会更好一些。

class Solution{
	class TrieNode{
		TrieNode[] children;
		boolean hasWord;
		String word;
		public TrieNode(){
			children = new TrieNode[26];
			isWord = false;
		}
	}
	private TrieNode root;
	public WordDictionary() {
        root = new TrieNode();
    }
    public void addWord(String word){
		TrieNode p = root;
		for(int i = 0;i < word.length();i++){
			int index = word.charAt(i)-'a';
			if(p.children[index] == null){
				p.children[index] = new TrieNode();
			}
			p = p.children[index];
		}
		p.isWord = true;
		p.word = word;
	}
	
	public boolean search(String word){
		return find(word,root,0);
	}
	public boolean find(String word, TrieNode root,int index){
		if(index == word.length())return root.hasWord;
		if(word.charAt(i) == '.'){
			for(TrieNode temp:root.children){
				if(temp != null && find(word,temp,index+1)){
					return true;
				}
			}
		}else{
			int j = word.charAt(index)-'a';
			Trie temp = root.children[j];
			return (temp != null && find(word,temp,index+1);
		}
	}
}

Word Search II

这一题在leetcode里面标注得难度是hard,因为同时考察了DFS和Trie,给一个二维char数组,还有一个string数组,要求找到string数组中可以在二维char里面可以组成得string.

在这里插入图片描述

public class Solution{
	Set<String> res = new HashSet<>():
	public List<String> findWords(char[][] board, String[] words){
			Trie trie = new Trie();
        for (String word : words) {
            trie.insert(word);
        }
        
        int m = board.length;
        int n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dfs(board, visited, "", i, j, trie);
            }
        }
        
        return new ArrayList<String>(res);
	}
	protected  void dfs(int[][] board, boolean[][] visited, String str, int x, int y,Trie trie){
		if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) return;
        if (visited[x][y]) return;
		str += board[x][y];
        if (!trie.startsWith(str)) return; //没有当前单词
        //找到了当前单词
        if (trie.search(str)) {
            res.add(str);
        }
        //开始DFS
        visited[x][y] = true;
        dfs(board, visited, str, x - 1, y, trie);
        dfs(board, visited, str, x + 1, y, trie);
        dfs(board, visited, str, x, y - 1, trie);
        dfs(board, visited, str, x, y + 1, trie);
        visited[x][y] = false
	}
	class TrieNode{
		TrieNode[] children = new TrieNode[26];
		boolean isWord;
		String word = "";
	}
	class Trie{
		public Trie(){
			public TrieNode root = new TrieNode();
		}
	
		public void insert(String word){
			TrieNode node = root;
			for(char c:word.toCharArray()){
				if(node.children[c-'a'] == null){
					node.children[c-'a'] = new TrieNode();
				}
				node = node.children[c-'a'];
			}
			node.word = word;
		}
		public boolean search(String word){
			TrieNode node = root;
        	for (char c : word.toCharArray()) {
            	if (node.children[c - 'a'] == null) return false;
            	node = node.children[c - 'a'];
        	}
        	return node.item.equals(word);
		}
		public boolean startsWith(String prefix){
			TrieNode node = root;
			for(char c: prefix.toCharArray()){
				if(node.children[c-'a'] == null)return false;
				node = node.children[c-'a'];
			}
			return true;
		}
	}
}

第二题确实有一点难,不过也就是代码量比较大

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值