力扣676.实现一个魔法字典

力扣676.实现一个魔法字典

  • 字典树 + dfs

cpp 复制代码
  class Trie
  {
      public:
      Trie* next[26];
      bool is_end = false;
  };
  class MagicDictionary {
  public:
      Trie* root = new Trie();
      
      void add(string& word)
      {
          Trie* p = root;
          for(char c:word)
          {
              if(p->next[c-'a'] == NULL) p->next[c-'a'] = new Trie();
              p = p->next[c-'a'];
          }
          p->is_end = true;
      }
      //idx为下标 , cnt为可以修改的字符数量 初始为1
      bool dfs(string& word,int idx,Trie* cur,int cnt)
      {
          //cnt必须为0,并且字符串必须结束
          if(idx == word.size()) return cnt == 0 && cur->is_end;
          for(int i=0;i<26;i++)
          {
              if(cur->next[i] == NULL) continue;
              //如果idx位匹配,继续下一个
              if(i == word[idx] - 'a')
              {
                  if(dfs(word,idx+1,cur->next[i],cnt)) return true;
              }
              //如果idx位不匹配,如果还能修改,就修改继续下一个
              else if(cnt>0 && dfs(word,idx+1,cur->next[i],cnt-1)) return true;
          }
          return false;
      }
      void buildDict(vector<string> dictionary) {
          for(string &word:dictionary)
              add(word);
      }
      
      bool search(string searchWord) {
          return dfs(searchWord,0,root,1);
      }
  };
相关推荐
mit6.8245 小时前
bfs|栈
算法
CoderYanger6 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz6 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
夏鹏今天学习了吗6 小时前
【LeetCode热题100(72/100)】前 K 个高频元素
leetcode
稚辉君.MCA_P8_Java6 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*6 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
.YM.Z7 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
Chat_zhanggong3458 小时前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法
百***48078 小时前
【Golang】slice切片
开发语言·算法·golang
墨染点香8 小时前
LeetCode 刷题【172. 阶乘后的零】
算法·leetcode·职场和发展