181、实现一个魔法字典

本文介绍了一种魔法字典的实现方法,利用前缀树进行单词的存储和搜索,支持通过更改单个字母来查找字典中是否存在新单词的功能。详细解释了前缀树的构建和搜索过程,以及如何判断单词是否符合搜索条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:
实现一个带有buildDict, 以及 search方法的魔法字典。

对于buildDict方法,你将被给定一串不重复的单词来构建一个字典。

对于search方法,你将被给定一个单词,并且判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。

示例 1:

Input: buildDict([“hello”, “leetcode”]), Output: Null
Input: search(“hello”), Output: False
Input: search(“hhllo”), Output: True
Input: search(“hell”), Output: False
Input: search(“leetcoded”), Output: False
注意:

你可以假设所有输入都是小写字母 a-z。
为了便于竞赛,测试所用的数据量很小。你可以在竞赛结束后,考虑更高效的算法。
请记住重置MagicDictionary类中声明的类变量,因为静态/类变量会在多个测试用例中保留。 请参阅这里了解更多详情。

依然使用的是前缀树,需要注意的是如果里面有hello和hallo这时候hello就是符合条件的,因此返回true
代码:

class Mytree {
	boolean isend;
	Mytree child[] = new Mytree[26];
}
class MagicDictionary {
	Mytree root;
	public MagicDictionary() {
		root = new Mytree();
	}
	public void buildDict(String[] dict) {
		for (String string : dict) {
			Mytree tree = root;
			for (int i = 0; i < string.length(); i++) {
				if (tree.child[string.charAt(i) - 'a'] == null) {
					tree.child[string.charAt(i) - 'a'] = new Mytree();
				}
				tree = tree.child[string.charAt(i) - 'a'];
			}
			tree.isend = true;
		}
	}
	public boolean search(String word) {
		Mytree tree = root;
		boolean flag = false;
		for (int i = 0; i < word.length(); i++) {
			if (tree.child[word.charAt(i) - 'a'] == null) {
				flag = true;
				for (int j = 0; j < 26; j++) {
					if (tree.child[j] != null) {
						tree = tree.child[j];
						if (issearch(word.substring(i + 1), tree)) {
							return true;
						}
					}
				}
			} else {
				tree = tree.child[word.charAt(i) - 'a'];
			}
		}
        tree = root;
		for (int i = 0; i < word.length(); i++) {
//			尝试一个个替换一下
			char tem = word.charAt(i);
			for (int j = 0; j < 25; j++) {
				if(tree.child[j] != null && j != tem - 'a'){
					if(issearch(word.substring(i + 1), tree.child[j])){
						return true;
					}
				}
			}
            if(tree.child[tem - 'a'] != null){
				tree = tree.child[tem - 'a'];
			}else {
				return false;
			}
		}
		return false;
	}
	public boolean issearch(String word, Mytree root) {
		for (int i = 0; i < word.length(); i++) {
			if(root.child[word.charAt(i) - 'a'] == null){
				return false;
			}else {
				root = root.child[word.charAt(i) - 'a'];
			}
		}
		return root.isend;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值