来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/
一.问题描述
给定一个字符串s
和一些 长度相同 的单词 words
。找出 s 中恰好可以由 words
中所有单词串联形成的子串的起始位置。
注意子串要与words
中的单词完全匹配,中间不能有其他字符 ,但不需要考虑 words
中单词串联的顺序。
示例 1:
输入:s = “barfoothefoobarman”, words = [“foo”,“bar”]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 “barfoo” 和 “foobar” 。
输出的顺序不重要, [9,0] 也是有效答案。
二.解题思路分析与代码
方法一:朴素方法求解
1. 分析
对于求串联单词所有的子串,首先想到的暴力方法就是,每次都截取和words
中所有单词拼接起来相同长度的串str
,然后,开始比较当前str
,是否是由words
中的所有串拼接而成的,如果是,则记下当前的索引作为答案.
本题,由于单词的长度是一样的,所以我们可以将截取出来的str
中截取出一段一段的单词,然后和words
中比较是否相等。这里我们可以借用哈希表。
定义两个哈希表,一个是words
的,另一个是将截取出来的字符串str
中所截的一个一个等长的单词。
代码实现如下:
lass Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> findSubstring(String s, String[] words) {
Map<String, Integer> map = new HashMap<>();
int len = words.length, one_len = words[0].length(), s_len = s.length();
int total_len = one_len * len;
for(String word : words){
map.put(word, map.getOrDefault(word,0) + 1);
}
// 开始的索引
for(int i = 0; i < s_len - total_len + 1