[leetcode] 472. 连接词

在这里插入图片描述

字典树

struct TrieNode
{
    bool isEnd;
    TrieNode *next[26];
    TrieNode()
    {
        isEnd = false;
        memset(next, 0, sizeof(next));
    }
};
class Trie
{
    TrieNode* root;
public:
    Trie()
    {
        root = new TrieNode();
    }
    void add(string word)
    {
        TrieNode *node = root;
        for(int i = 0; i < word.size(); i++)
        {
            char ch = word[i];
            if(node->next[ch - 'a'] == NULL)
            {
                node->next[ch - 'a'] = new TrieNode();
            }
            node = node->next[ch - 'a'];
        }
        node->isEnd = true;
    }
  
    bool check(string& word,int count,int start)
    {
        TrieNode *node = root;
        for(int i = start; i < word.size(); i++)
        {
            if(node->next[word[i] - 'a'] == NULL) return false;
            node = node->next[word[i] - 'a'];
            if(node->isEnd == true)
            {
                if(i == word.size()-1) return count >= 1;
                if(check(word, count+1, i + 1)) return true;
            }
        }
        return false;
    }
};

class Solution {
public:
    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
        Trie dict;
        vector<string>res;
        for(int i = 0; i < words.size(); i++)
        {
            dict.add(words[i]);
        }
        for(int i = 0; i < words.size(); i++)
        {
            if(dict.check(words[i], 0, 0) == true)
            {
                res.push_back(words[i]);
            }
        }
        return res;
    }
};

check那里:

在这里插入图片描述

bool check(string& word,int count,int start)
{
     TrieNode *node = root;
     for(int i = start; i < word.size(); i++)
     {
         if(node->next[word[i] - 'a'] == NULL) return false; // abc虽然可以拆成a、b,count也大于1但c并不存在,所以会回溯到上一层
         node = node->next[word[i] - 'a'];
         if(node->isEnd == true)
         {
             if(i == word.size()-1) return count >= 1;		//要到末尾才能判断,单词必须完全被拆分,count==0表示只有一个单词
             if(check(word, count+1, i + 1)) return true; //递归下去,如果不成功会回到本层
         }
     }
     return false;
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值