Java implementation LeetCode 676 to achieve a magic dictionary (violence)

676. implement a magic dictionary

Implement a dictionary with a magic buildDict, and search methods.

For buildDict method, you will be given a string of non-repetition of the word to build a dictionary.

For search method, you will be given a word, and it is determined whether only one letter of the word into another letter, so that the formed new word exists in the dictionary you build.

Example 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

note:

You may assume that all inputs are lowercase letters az.
To facilitate competition, the amount of data used in the test is small. You can at the end of the competition, consider a more efficient algorithm.
Remember to reset MagicDictionary class variables declared in the class, because the static / class variables will remain in several test cases. See here for more details.

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);
 */
Released 1727 original articles · won praise 30000 + · views 3.56 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105311617