日期:2022/8/6
题目描述:给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的子字符串的所有单词。
如果你可以删除 words[j] 最左侧和/或最右侧的若干字符得到 word[i] ,那么字符串 words[i] 就是 words[j] 的一个子字符串。
示例:
输入:words = ["mass","as","hero","superhero"]
输出:["as","hero"]
解释:"as" 是 "mass" 的子字符串,"hero" 是 "superhero" 的子字符串。
["hero","as"] 也是有效的答案。
输入:words = ["leetcode","et","code"]
输出:["et","code"]
解释:"et" 和 "code" 都是 "leetcode" 的子字符串。
输入:words = ["blue","green","bu"]
输出:[]
思路:
一个个比较就完事了
代码+解析:
class Solution {
public:
vector<string> stringMatching(vector<string>& words) {
vector<string> res;
for(int i=0; i<words.size(); i++){
for(int j=0; j<words.size(); j++){
if(i!=j && words[j].find(words[i]) != string::npos ){
res.push_back(words[i]);
break;
}
}
}
return res;
}
};
学到的总结:
- words[j].find(words[i]) != string::npos