Keshawn_lu's Blog

Leetcode 1408. 数组中的字符串匹配

字数统计: 416阅读时长: 1 min
2022/08/06 Share

题目简介:

给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的子字符串的所有单词。

如果你可以删除 words[j] 最左侧和/或最右侧的若干字符得到 word[i] ,那么字符串 words[i] 就是 words[j] 的一个子字符串。

示例 1:

1
2
3
4
输入:words = ["mass","as","hero","superhero"]
输出:["as","hero"]
解释:"as" 是 "mass" 的子字符串,"hero" 是 "superhero" 的子字符串。
["hero","as"] 也是有效的答案。

示例 2:

1
2
3
输入:words = ["leetcode","et","code"]
输出:["et","code"]
解释:"et" 和 "code" 都是 "leetcode" 的子字符串。

示例 3:

1
2
输入:words = ["blue","green","bu"]
输出:[]

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 30
  • words[i] 仅包含小写英文字母。
  • 题目数据 保证 每个 words[i] 都是独一无二的。

思路:

暴力寻找即可,需要注意的是防止一个单词被多次加入答案数组,创建一个map来控制。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
vector<string> stringMatching(vector<string>& words) {

vector<string> res;
map<string, int> count;

for(int i = 0; i < words.size(); i++){

for(int j = i + 1; j < words.size(); j++){

if(words[i].find(words[j]) != string::npos && count[words[j]] == 0){

count[words[j]] = 1;
res.push_back(words[j]);
}

if(words[j].find(words[i]) != string::npos && count[words[i]] == 0){

count[words[i]] = 1;
res.push_back(words[i]);
}

}
}

return res;

}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: