持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第7天,点击查看活动详情
一、题目描述:
1408. 数组中的字符串匹配 - 力扣(LeetCode)
给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的子字符串的所有单词。
如果你可以删除 words[j] 最左侧和/或最右侧的若干字符得到 word[i] ,那么字符串 words[i] 就是 words[j] 的一个子字符串。
示例 1:
输入:words = ["mass","as","hero","superhero"]
输出:["as","hero"]
解释:"as" 是 "mass" 的子字符串,"hero" 是 "superhero" 的子字符串。
["hero","as"] 也是有效的答案。
示例 2:
输入:words = ["leetcode","et","code"]
输出:["et","code"]
解释:"et" 和 "code" 都是 "leetcode" 的子字符串。
示例 3:
输入:words = ["blue","green","bu"]
输出:[]
提示:
- 1 <= words.length <= 100
- 1 <= words[i].length <= 30
- words[i] 仅包含小写英文字母。
- 题目数据 保证 每个 words[i] 都是独一无二的。
二、思路分析:
对每个字符串暴力搜索就行,复杂度,K是字符串的长度。 如果要稍微剪枝的话从两个方向考虑。
- 一个串如果是另一个串的子串,就不用继续查找了,这很容易想到。
- 一个串如果被作为子串插入过,那么这个串就不需要作为父串来被别的串查找了,这也很容易想到。 不过看起来剪枝意义不大,比赛时候提交的剪枝前4ms,比赛结束提交的剪枝后8ms,还赶不上服务器波动。 看到有人说把所有字符串拼接成一个大字符串,其实和暴力的时间复杂度是一样的。毕竟搜索两个短字符串和一个长字符串都一样。
三、AC 代码:
class Solution {
public:
vector<string> stringMatching(vector<string>& words) {
vector<string> result;
vector<bool> inserted(words.size(),false);
for(int i=0;i<words.size();i++){
for(int j=0;j<words.size();j++){
if(i==j || inserted[j]) continue;
if(words[j].find(words[i])!=string::npos){
result.push_back(words[i]);
inserted[i]=true;
break;
}
}
}
return result;
}
};