zoukankan      html  css  js  c++  java
  • [leetcode-676-Implement Magic Dictionary]

    Implement a magic directory with buildDict, and search methods.

    For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary.

    For the method search, you'll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.

    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:

    1. You may assume that all the inputs are consist of lowercase letters a-z.
    2. For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
    3. Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details.

    思路:

    用一个map记录长度为len的所有字符串,当search的时候根据字符串的长度,找到所有相同字符串的长度,然后统计map里的字符串与要

    查询的字符串字符差异个数。

    也可以用一个set保存所有字符串,search的时候将字符串每一位都进行a-z的替换,随时查看是否在set里面即可。

     
     map<int,vector<string>>mp;
     
     MagicDictionary()
     {
            mp.clear();
     }
        
        /** Build a dictionary through a list of words */
        void buildDict(vector<string> dict) {
            if(dict.size()==0)return;
        for(auto s:dict)
        {
          mp[s.length()].push_back(s);
        }
        }
        
        /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
        bool search(string word) {
            int len = word.length();
        int diff =0;
        if(mp[len].size()==0)return false;
        
        for(int i=0;i<mp[len].size();i++)
        {
          diff==0;
          for(int j =0;j<mp[len][i].length();j++)
          {
            if(word[j]!=mp[len][i][j])diff++;
          }
          if(diff==1 )return true;      
        }
        return false;
        }
  • 相关阅读:
    JSP----获取表单参数
    application 从web.xml中获取初始化参数
    使用定时器分解任务
    无阻塞加载外部js(动态脚本元素,XMLHttpRequest注入,LazyLoad)
    ReactJs 入门DEMO(转自别人)
    带你一分钟理解闭包--js面向对象编程(转载他人)
    使用SqlBulkCopy进行批量数据插入
    AngularJsDEMO
    ECharts
    C#发送邮件DEMO
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/7500606.html
Copyright © 2011-2022 走看看