zoukankan      html  css  js  c++  java
  • 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);
     */
    
  • 相关阅读:
    泛微协同OA制造业解决方案
    泛微协同OA房地产行业解决方案
    基于内置web工作流的政府OA解决方案
    泛微协同OA广告行业解决方案
    成功导入数据
    首页做完了
    终于知道如何才能取得HtmlEditor里的数据了
    国庆放假了!
    最近这两天
    Dictionary<string, string>是一个泛型使用说明
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946293.html
Copyright © 2011-2022 走看看