力扣648.单词替换

力扣648.单词替换

  • 字典树

    • 构建字典树
    • 遍历每个字母判断操作
  •   class Solution {
          struct Trie{
              bool isEnd = false;
              Trie* next[26] = {0};
          };
      public:
          string replaceWords(vector<string>& dictionary, string sentence) {
              Trie* trie = new Trie();
              for(auto& dict:dictionary)
              {
                  Trie* node = trie;
                  for(char c:dict)
                  {
                      if(node->next[c-'a'] == NULL)
                          node->next[c -'a'] = new Trie();
                      node = node->next[c-'a'];
                  }
                  node->isEnd = true;
              }
              string result = "";
              Trie* node = trie;
              int i = 0;
              while(i<sentence.size())
              {
                  //如果是字典中的字符串并且到结尾了
                  if(node->isEnd)
                  {
                      node = trie;
                      while(sentence[i] != ' ' && i < sentence.size())
                          i ++;
                      continue;
                  }
                  if(sentence[i] == ' ')
                  {
                      result += " ";
                      node = trie;
                      i++;
                      continue; 
                  }
                  //如果是不在字典中的单词 直接全部加到答案里
                  if(node->next[sentence[i] - 'a'] == NULL)
                  {
                      while(sentence[i] != ' ' && i < sentence.size())
                      {
                          result += sentence[i];
                          i ++;
                      }
                  }
                  //在字典中的单词 一个一个加
                  else if(node->next[sentence[i] - 'a'] != NULL)
                  {
                      result += sentence[i];
                      node = node->next[sentence[i] - 'a'];
                      i++;
                  }
              }
              return result;
          }
      };
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阳光男孩01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值