力扣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);
      }
  };
相关推荐
smj2302_7968265212 分钟前
解决leetcode第3869题.统计区间内奇妙数的数目
python·算法·leetcode
TracyCoder12326 分钟前
LeetCode Hot100(66/100)——118. 杨辉三角
算法·leetcode·职场和发展
葳_人生_蕤28 分钟前
Leetcode HOT 100
算法·leetcode·职场和发展
仟濹35 分钟前
【算法打卡day23(2026-03-15 周日)今日算法or技巧:双指针 & 链表 & 回溯算法】6个题
数据结构·算法·链表
靠沿1 小时前
【优选算法】专题十四——优先级队列
算法
无尽的罚坐人生1 小时前
hot 100 35. 搜索插入位置
数据结构·算法·leetcode·二分查找
葳_人生_蕤1 小时前
力扣Hot100——234.回文链表
算法·leetcode·链表
自信150413057591 小时前
数据结构之实现链式结构二叉树
c语言·数据结构·算法
Barkamin1 小时前
堆排序简单实现
java·数据结构·算法·排序算法
迈巴赫车主1 小时前
天梯赛 L2-004 这是二叉搜索树吗?java
java·开发语言·数据结构·算法·天梯赛