力扣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);
      }
  };
相关推荐
NAGNIP6 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队7 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja12 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下12 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶12 小时前
算法 --- 字符串
算法
博笙困了12 小时前
AcWing学习——差分
c++·算法
NAGNIP12 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP12 小时前
大模型微调框架之LLaMA Factory
算法
echoarts12 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客12 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法