472. Concatenated Words

博客介绍了一种处理字符串的方法。给定数组元素数量不超10000,元素长度总和不超600000,输入仅含小写字母。采用递归方法,类似word break,先确认左半部分可查,再递归拆解右半部分,查找前删掉单词本身。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

472. Concatenated Words


Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.

Example:

Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]

Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]

Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; 
 "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; 
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".

Note:

  1. The number of elements of the given array will not exceed 10,000
  2. The length sum of elements in the given array will not exceed 600,000.
  3. All the input string will only include lower case letters.
  4. The returned elements order does not matter.

方法1: recursion

思路:

和word break一样,先取左边确认可查,然后递归拆解右半部分。这里需要在每次查找前把单词本身删掉,也不需要查找单词自身(左右空子串的情况都不用考虑),

class Solution {
public:
    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
        unordered_set<string> dict(words.begin(), words.end());
        vector<string> result;
        for (auto word: words) {
            dict.erase(dict.find(word));
            if (findAllHelper(word, dict)) {
                result.push_back(word);
            }
            dict.insert(word);
        }
        return result;
    }
    
    bool findAllHelper(string s, unordered_set<string> & dict) {
        if (dict.count(s)) return true;
        
        for (int i = 1; i < s.size(); i++) {
            string left = s.substr(0, i);
            string right = s.substr(i);
            if (dict.count(left) && findAllHelper(right, dict)) {
                return true;
            }
        }
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值