30.串联所有单词的子串
串联所有单词的子串
给定一个字符串 s 和一个字符串数组 words。words 中所有字符串 长度相同。
s 中的 串联子串 是指一个包含 words 中所有字符串以任意顺序排列连接起来的子串。
返回所有串联子串在 s 中的开始索引。你可以以 任意顺序 返回答案。
示例 1:
输入:s = “barfoothefoobarman”, words = [“foo”,”bar”]
输出:[0,9]
示例 2:
输入:s = “wordgoodgoodgoodbestword”, words = [“word”,”good”,”best”,”word”]
输出:[]
示例 3:
输入:s = “barfoofoobarthefoobarman”, words = [“bar”,”foo”,”the”]
输出:[6,9,12]
提示:
- 1 <= s.length <= $10^4$
- 1 <= words.length <= 5000
- 1 <= words[i].length <= 30
解析
因为 words 中所有单词长度相同,可以利用滑动窗口,以单词长度为步长滑动。
1 | /** |
对每个起始位置,依次截取等长单词并与目标单词集合比较。时间复杂度 O(n * m * k),其中 n 为字符串长度,m 为单词个数,k 为单词长度。
30.串联所有单词的子串
https://leetcode.lz5z.com/30.substring-with-concatenation-of-all-words/