题意
给定一个字符串的列表,列表中的一些字符串能够由列表中的另外一些字符串拼接而成(至少两个)。问能够被拼接的字符串有哪些。
思路
其实和wordBreak那道题一样,只不过我们需要遍历一下待拼接的那个字符串。然后剩下的就是wordBreak一样了。
细节
注意我们用unordered_set
来判断字符串是否存在的时候要注意去掉自身。
代码
const int maxn = 10005;
int d[maxn];
class Solution {
public:
unordered_set<string> has;
int dfs(string s, int i) {
if (d[i] != -1) return d[i];
int ans = 0;
if (s.substr(0, i + 1) != s && has.count(s.substr(0, i+ 1))) ans = 1;
else {
for (int j = 0; j < i; j++) {
if (ans) break;
if (s.substr(j + 1, i - j) != s && has.count(s.substr(j + 1, i - j))) ans = dfs(s, j);
}
}
return ans;
}
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
vector<string> ans;
for (auto x : words) has.insert(x);
int n = words.size();
if (n) {
memset(d, -1, sizeof(d));
for (int i = 0; i < n; i++) {
if (words[i].length() && dfs(words[i], words[i].length() - 1)) {
ans.push_back(words[i]);
}
}
}
return ans;
}
};