「每日LeetCode」2021年1月18日

本文最后更新于:2023年3月19日 晚上

Lt1408. 数组中的字符串匹配

1408. 数组中的字符串匹配

给你一个字符串数组 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] 都是独一无二的。

思路

按字符串长度从小到大排序,使用一个 set 存储单词,遍历数组,判断当前单词是否包含 set 中都某一个单词,是的话将那个单词加入结果 set 中,判断完后将当前单词加入单词 set 中。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param {string[]} words
* @return {string[]}
*/
var stringMatching = function (words) {
const res = new Set();
const map = new Set();
words.sort((a, b) => a.length - b.length);
console.log(words);
for (const word of words) {
[...map.values()].forEach((element) => {
if (word.includes(element)) res.add(element);
});
map.add(word);
}
return [...res.values()];
};

console.log(stringMatching(["leetcoder", "leetcode", "od", "hamlet", "am"]));