力扣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);
      }
  };
相关推荐
向阳逐梦5 分钟前
PID控制算法理论学习基础——单级PID控制
人工智能·算法
2zcode8 分钟前
基于Matlab多特征融合的可视化指纹识别系统
人工智能·算法·matlab
Owen_Q26 分钟前
Leetcode百题斩-二分搜索
算法·leetcode·职场和发展
矢志航天的阿洪1 小时前
蒙特卡洛树搜索方法实践
算法
UnderTheTime1 小时前
2025 XYD Summer Camp 7.10 筛法
算法
zstar-_1 小时前
Claude code在Windows上的配置流程
笔记·算法·leetcode
圆头猫爹2 小时前
第34次CCF-CSP认证第4题,货物调度
c++·算法·动态规划
秋说2 小时前
【PTA数据结构 | C语言版】出栈序列的合法性
c语言·数据结构·算法
用户40315986396632 小时前
多窗口事件分发系统
java·算法
用户40315986396632 小时前
ARP 缓存与报文转发模拟
java·算法