1408. 数组中的字符串匹配
1408. 数组中的字符串匹配
🟢 🔖 数组 字符串 字符串匹配 🔗 力扣 LeetCode
题目
Given an array of string words, return all strings inwords that is asubstring of another word. You can return the answer in any order.
A substring is a contiguous sequence of characters within a string
Example 1:
Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.
Example 2:
Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".
Example 3:
Input: words = ["blue","green","bu"]
Output: []
Explanation: No string of words is substring of another string.
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 30words[i]contains only lowercase English letters.- All the strings of
wordsare unique.
题目大意
给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的子字符串的所有单词。
如果你可以删除 words[j] 最左侧和/或最右侧的若干字符得到 words[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 <= 1001 <= words[i].length <= 30words[i]仅包含小写英文字母。- 题目数据 保证 每个
words[i]都是独一无二的。
解题思路
将
words按照字符串长度从小到大排序。这样可以保证,较短的字符串总是优先被检查是否是其他字符串的子串。使用双重循环:
- 外层循环遍历每个字符串
words[i]。 - 内层循环从
i+1开始,检查后续字符串words[j]是否包含当前字符串words[i]。
- 外层循环遍历每个字符串
如果
words[j]包含words[i],将words[i]添加到结果数组res中,并跳出内层循环。返回结果数组
res。
复杂度分析
时间复杂度:
O(n log n + n^2 * m)- 对数组按长度排序的时间复杂度为
O(n log n),其中n是words的长度。 - 外层循环遍历
n个字符串,内层循环最多遍历n - 1次,字符串比较的复杂度为O(m),其中m是字符串的平均长度,双层循环的总时间复杂度为O(n^2 * m)。
- 对数组按长度排序的时间复杂度为
空间复杂度:
O(k),其中k是结果数组的长度,只使用了结果数组res和一些辅助变量。
代码
/**
* @param {string[]} words
* @return {string[]}
*/
var stringMatching = function (words) {
// 按字符串长度排序
words.sort((a, b) => a.length - b.length);
let res = [];
// 遍历每个字符串
for (let i = 0; i < words.length; i++) {
for (let j = i + 1; j < words.length; j++) {
// 检查是否为子字符串
if (words[j].indexOf(words[i]) !== -1) {
res.push(words[i]);
break;
}
}
}
return res;
};
相关题目
| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 2564 | 子字符串异或查询 | 位运算 数组 哈希表 1+ | 🟠 | 🀄️ 🔗 |
