LC 966. Vowel Spellchecker

Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.

For a given query word, the spell checker handles two categories of spelling mistakes:

  • Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist.

    • Example: wordlist = ["yellow"]query = "YellOw"correct = "yellow"
    • Example: wordlist = ["Yellow"]query = "yellow"correct = "Yellow"
    • Example: wordlist = ["yellow"]query = "yellow"correct = "yellow"
  • Vowel Errors: If after replacing the vowels (‘a‘, ‘e‘, ‘i‘, ‘o‘, ‘u‘) of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.
    • Example: wordlist = ["YellOw"]query = "yollow"correct = "YellOw"
    • Example: wordlist = ["YellOw"]query = "yeellow"correct = "" (no match)
    • Example: wordlist = ["YellOw"]query = "yllw"correct = "" (no match)

In addition, the spell checker operates under the following precedence rules:

  • When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.
  • When the query matches a word up to capitlization, you should return the first such match in the wordlist.
  • When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
  • If the query has no matches in the wordlist, you should return the empty string.

Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].

Example 1:

Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"]
Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"]

Note:

  • 1 <= wordlist.length <= 5000
  • 1 <= queries.length <= 5000
  • 1 <= wordlist[i].length <= 7
  • 1 <= queries[i].length <= 7
  • All strings in wordlist and queries consist only of english letters.

踩坑踩了一个下午,掉到坑里出不来了。

Runtime: 96 ms, faster than 100.00% of C++ online submissions for Vowel Spellchecker.

第一种是我的做法 修改了TrieNode的结构,让它带了一个case_sensitive的标志位。如果带上大小写搜索,

每次需要判断字符的大小写,这样得到的是第一种准确的搜索。如果不敏感,就全部放在小写的这个节点里。

为了满足题意,大小写不敏感的可能有多种,那么Trie节点带一个数组比较合适。

注意:

1. 本来的字典可能有重复,我去。。。

2. 需要返回最小的index,那就把所有的求出来以后再求最小的index。

写了一个下午。

class TrieNode{
public:
  string word;
  vector<string> wordlist;
  TrieNode* lowercase[26];
  TrieNode* uppercase[26];
  TrieNode(){
    for(int i=0; i<26; i++) lowercase[i] = nullptr;
    for(int i=0; i<26; i++) uppercase[i] = nullptr;
  }
};

class Trie{
public:
  TrieNode* root;
  Trie(const vector<string>& wordlist, bool case_sensitive = true){
    root = new TrieNode();
    BuildTrie(wordlist, case_sensitive);
  }
  void BuildTrie(const vector<string>& wordlist, bool case_sensitive = true){

    for(int i=0; i<wordlist.size(); i++){
      TrieNode* tmp = root;
      for(int j=0; j<wordlist[i].size(); j++){
        char tmpchar = wordlist[i][j];
        int idx = 0;
        if(!case_sensitive){
          if(tmpchar >= ‘A‘ && tmpchar <= ‘Z‘){
            idx = tmpchar - ‘A‘;
          }else idx = tmpchar - ‘a‘;
          if(!tmp->lowercase[idx]) tmp->lowercase[idx] = new TrieNode();
          tmp = tmp->lowercase[idx];
        }else{
          if(tmpchar >= ‘A‘ && tmpchar <= ‘Z‘){
            idx = tmpchar - ‘A‘;
            if(!tmp->uppercase[idx]) tmp->uppercase[idx] = new TrieNode();
            tmp = tmp->uppercase[idx];
          }else {
            idx = tmpchar - ‘a‘;
            if(!tmp->lowercase[idx]) tmp->lowercase[idx] = new TrieNode();
            tmp = tmp->lowercase[idx];
          }
        }
      }
      if(case_sensitive){
        tmp->word = wordlist[i];
      }else {
        tmp->wordlist.push_back(wordlist[i]);
      }
    }
  }
  bool hasword(string word, string& foundword, bool case_sensitive = true){
    TrieNode* tmp = root;
    locale loc;
    for(int i=0; i<word.size(); i++){
      char tmpchar = word[i];
      int idx = 0;
      if(!case_sensitive){
        tmpchar = tolower(tmpchar, loc);
        idx = tmpchar - ‘a‘;
        if(!tmp->lowercase[idx]) return false;
        tmp = tmp->lowercase[idx];
      }else {
        if(tmpchar >= ‘A‘ && tmpchar <= ‘Z‘) {
          idx = tmpchar - ‘A‘;
          if(!tmp->uppercase[idx]) return false;
          tmp = tmp->uppercase[idx];
        } else {
          idx = tmpchar - ‘a‘;
          if(!tmp->lowercase[idx]) return false;
          tmp = tmp->lowercase[idx];
        }
      }
    }
    if(!case_sensitive) {
      if(!tmp->wordlist.empty()){
        foundword = tmp->wordlist[0];
        return true;
      }
      return false;
    }
    if(!tmp->word.empty()) {
      foundword = tmp->word;
      return true;
    }
    return false;
  }
};

class Solution {
public:
  set<char> vset;
  unordered_map<string,int> mp;
  vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) {
    for(int i=0; i<wordlist.size(); i++){
      mp[wordlist[i]] = i;
    }
    vset.insert(‘a‘);vset.insert(‘e‘);vset.insert(‘i‘);
    vset.insert(‘o‘);vset.insert(‘u‘);
    vector<string> ret;
    Trie trie_case_sensi = Trie(wordlist);
    Trie trie_not_case_sensi = Trie(wordlist, false);
    for(int i=0; i<queries.size(); i++){
      string foundword;
      vector<string> foundwordvec;
      if(trie_case_sensi.hasword(queries[i],foundword)) {
        ret.push_back(queries[i]);
      }else if(trie_not_case_sensi.hasword(queries[i], foundword, false)){
        ret.push_back(foundword);
      }else {
        dfs(trie_not_case_sensi.root, queries[i], foundwordvec, 0);
        int minidx = wordlist.size();
        for(auto x : foundwordvec) minidx = min(minidx, mp[x]);
        if(minidx == wordlist.size()) ret.push_back("");
        else ret.push_back(wordlist[minidx]);
      }
    }
    return ret;
  }

  void dfs(const TrieNode* root,string query, vector<string>& ret, int start){
    if(start == query.size()){
      assert(!root->wordlist.empty());
      ret.push_back(root->wordlist[0]);
      return ;
    }
    std::locale loc;
    char c = tolower(query[start],loc);
    int idx = 0;
    idx = c - ‘a‘;
    if(vset.count(c)){
      for(auto it = vset.begin(); it != vset.end(); it++){
        char vsub = *it;
        int newidx = 0;
        newidx = vsub - ‘a‘;
        if(!root->lowercase[newidx]) continue;
        TrieNode* nextroot = root->lowercase[newidx];
        dfs(nextroot, query, ret, start+1);
      }
    }else{
      if(!root->lowercase[idx]) return ;
      TrieNode* nextroot = root->lowercase[idx];
      dfs(nextroot, query, ret, start+1);
    }
  }
};

下面看看网上的大神的解法,很简单,既然aeiou都能互相匹配,那就把aeiou变成#,这样一来不就行了么!真是厉害。

class Solution {
    public String[] spellchecker(String[] wordlist, String[] queries) {
        Set<String> words = new HashSet<>(Arrays.asList(wordlist));
        HashMap<String, String> cap = new HashMap<>();
        HashMap<String, String> vowel = new HashMap<>();
        for (String w : wordlist) {
            String lower = w.toLowerCase(), devowel = lower.replaceAll("[aeiou]", "#");
            cap.putIfAbsent(lower, w);
            vowel.putIfAbsent(devowel, w);
        }
        for (int i = 0; i < queries.length; ++i) {
            if (words.contains(queries[i])) continue;
            String lower = queries[i].toLowerCase(), devowel = lower.replaceAll("[aeiou]", "#");
            if (cap.containsKey(lower)) {
                queries[i] = cap.get(lower);
            } else if (vowel.containsKey(devowel)) {
                queries[i] = vowel.get(devowel);
            } else {
                queries[i] = "";
            }
        }
        return queries;
    }
}

原文地址:https://www.cnblogs.com/ethanhong/p/10199989.html

时间: 2024-07-31 07:28:18

LC 966. Vowel Spellchecker的相关文章

【leetcode】966. Vowel Spellchecker

题目如下: Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: Capitalization: If the query matches a word in the word

[Swift Weekly Contest 117]LeetCode966.元音拼写检查 | Vowel Spellchecker

Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: Capitalization: If the query matches a word in the wordlist (

Leetcode-966 Vowel Spellchecker(元音拼写检查器)

1 #define _for(i,a,b) for(int i = (a);i < (b);i ++) 2 class Solution 3 { 4 public: 5 vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) 6 { 7 vector<string> rnt; 8 set<string> ws; 9 map&

Lc.exe已退出 代码为-1

今天使用vs2010开发,有人在vss项目中增加了一个第三方组件,后来删除了,我的计算机上没有这个第三方组件,结果导致了LC.exe错误:"Lc.exe已退出 代码为-1 " 解决方法: 1.把项目文件夹下Properties文件夹下的licenses.licx文件删除,重新编译即可: 2.文本方式打开*.csproj文件,在文件中查找licenses.licx字样,删除对应节点. 注意:还有一种情况就是Properties文件夹下已经没有licenses.licx文件了,程序还是报这

chkrootkit 编译报错的解决/usr/bin/ld: cannot find -lc

1:Centos6.5安装chkrootkit wget ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz tar xvf chkrootkit.tar.gz cd chkrootkit-0.51/ make sense报错如下: /usr/bin/ld: cannot find -lc collect2: ld returned 1 exit status make: *** [strings-static] Error 1 2:解决

POJ1035 Spell-checker(哈希,串处理)

本文出自:http://blog.csdn.net/svitter 题意: 检查字典. 一开始,输入字典中的字符,以#结束. 随后,输入查询的字符,以#结束. 其中,符合要求的查询项目有: 1.去除一个字符,可以匹配 2.取代一个字符,可以匹配 3.添加一个字符,可以匹配 输入输出分析: 1.注意不要将#包含进入字典. 2.对于每一个字符进行分析. 题目分析: 使用哈希表或者直接暴力解题. 一个字符指针指向要查询的单词,一个字典指针指向字典中的单词. 分为三种处理情况: 1.对于去除一个字符的情

错误为Lc.exe已退出,代码为-1

近来在做项目的时候,突然遇到 了 LC.exe 已退出,代码为-1 的提示,怎么也编译不了,在查了相关的资料后,终于明白了原因,其解决方案如下 : 1. 以管理员的身份来运行vs, 并把项目中“properties”目录下的“license.licx”文件删除,再编译就成功了. 2. 注册第三方组件或使用破解版 3. 将破解版的哪个组件使用lidism给翻译成il语言,然后用ilasm重新编译成dll,在编译的时候加入  /key=[你的强名称文件].snk 参数,然后使用VS重新编译 其原因如

【转】G++ 处理 /usr/bin/ld: cannot find -lc

原文网址:http://blog.sina.com.cn/s/blog_67bbb71101010tto.html 用g++编译C++程序时显示出:/usr/lib/ld: cannot find -lc/usr/lib/ld: cannot find -lgcc_s/usr/lib/ld: cannot find -lm/usr/lib/ld: cannot find -lgcc_s的错误.在网上看了很多中关于/usr/lib/ld: cannot find -lXXX的解法,但是大同小异,没

解决“错误为Lc.exe已退出,代码为-1”

今天做项目的时候突然出现编译不通过,错误为Lc.exe已退出,代码为-1. 网查了一下,原因是项目中使用了第三方组件(Developer Express v2011)造成的,分享如下: 这个第三方组件是个商业组件,他在组件的主使用类定义了 LicenseProvider(typeof(LicFileLicenseProvider)) 这个Attribute. VS在编译时检测到这个类的时候,会检查到组件使用的是LicFileLicenseProvider这个属性,表示有组件使用的是把许可的辅助信