跳至主要內容

1408. 数组中的字符串匹配


1408. 数组中的字符串匹配

🟢   🔖  数组 字符串 字符串匹配  🔗 力扣open in new window LeetCodeopen in new window

题目

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 <= 100
  • 1 <= words[i].length <= 30
  • words[i] contains only lowercase English letters.
  • All the strings of words are 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 <= 100
  • 1 <= words[i].length <= 30
  • words[i] 仅包含小写英文字母。
  • 题目数据 保证 每个 words[i] 都是独一无二的。

解题思路

  1. words 按照字符串长度从小到大排序。这样可以保证,较短的字符串总是优先被检查是否是其他字符串的子串。

  2. 使用双重循环:

    • 外层循环遍历每个字符串 words[i]
    • 内层循环从 i+1 开始,检查后续字符串 words[j] 是否包含当前字符串 words[i]
  3. 如果 words[j] 包含 words[i],将 words[i] 添加到结果数组 res 中,并跳出内层循环。

  4. 返回结果数组 res

复杂度分析

  • 时间复杂度O(n log n + n^2 * m)

    • 对数组按长度排序的时间复杂度为 O(n log n),其中 nwords 的长度。
    • 外层循环遍历 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+🟠🀄️open in new window 🔗open in new window