LeetCode472. 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.

参考资料:here

class Solution {
private:
	struct Node {
		bool end;
		vector<Node*> next;
		Node() :end(false){
			next = vector<Node*>(26, NULL);
		}
	};
	Node *root;
	void addWord(string &s) {
		Node* curr = root;
		for (char c : s) {
			int idx = c - 'a';
			if (curr->next[idx] == NULL)
				curr->next[idx] = new Node();
			curr = curr->next[idx];
		}
		curr->end = true;
	}
	bool helper(string &word, int start, int count) {
		Node* curr = root;
		for (int i = start; i < word.size(); i++) {
			int idx = word[i] - 'a';
			if (curr->next[idx] == NULL) return false;
			if (curr->next[idx]->end) {
				if (i == word.size() - 1) return count >= 1;
				if (helper(word, i + 1, count + 1)) return true;
			}
			curr = curr->next[idx];
		}
		return false;
	}
public:
	vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
		vector<string> ans;
        root = new Node();
		for (string word : words) addWord(word);
		for (string word : words) {
			if (helper(word, 0, 0)) ans.push_back(word);
		}
		return ans;
	}
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值