就是一个花里胡哨的菜逼题目
实现一个带有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类中声明的类变量,因为静态/类变量会在多个测试用例中保留。 请参阅这里了解更多详情。
太简单了不写题解了
class MagicDictionary {
String dic[];
int N;
/** Initialize your data structure here. */
public MagicDictionary() {
N=0;
}
/** Build a dictionary through a list of words */
public void buildDict(String[] dict) {
int i,len=dict.length;
N=len;
dic=new String[len];
for(i=0;i<len;i++) {
String s=dict[i];
dic[i]=s;
}
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
public boolean search(String word) {
int i,j,len=word.length();
char ch[]=word.toCharArray();
for(j=0;j<N;j++) {
if(dic[j].length()==len) {
int count=0;
char ch1[]=dic[j].toCharArray();
for(i=0;i<len;i++) {
if(ch[i]!=ch1[i])
count++;
if(count>1)
break;
}
if(i==len&&count==1)
return true;
}
}
return false;
}
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dict);
* boolean param_2 = obj.search(word);
*/