Java实现 LeetCode 676 实现一个魔法字典(暴力)

676. 实现一个魔法字典

实现一个带有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 {
   List<String> list;
    /** Initialize your data structure here. */
    public MagicDictionary() {
        list=new ArrayList();
    }
    
    /** Build a dictionary through a list of words */
    public void buildDict(String[] dict) {
       for(int i=0;i<dict.length;i++){
           list.add(dict[i]);
       }
    }
    
    /** 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 size=list.size();
        int n=word.length();
        for(int i=0;i<size;i++){
            String cur=list.get(i);
            if(cur.length()==n&&notSameOne(cur,word)){
                 return true;
            }
        } 
        return false; 
    }
    public boolean notSameOne(String str1,String str2){
         int n=str1.length();
         int disCout=0;
         for(int i=0;i<n;i++){
             if(str1.charAt(i)!=str2.charAt(i)){
                 disCout++;
             }
             if(disCout>1) return false; 
         }

         return disCout==1?true:false;  
    }
}

/**
 * Your MagicDictionary object will be instantiated and called as such:
 * MagicDictionary obj = new MagicDictionary();
 * obj.buildDict(dict);
 * boolean param_2 = obj.search(word);
 */
原文地址:https://www.cnblogs.com/a1439775520/p/13075187.html