Leetcode(30) Substring with Concatenation of All Words

Description:

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Input: s = “barfoothefoobarman”, words = [“foo”,”bar”] Output: [0,9]

Example 2:

Input: s = “wordgoodstudentgoodword”, words = [“word”,”student”] Output: []

解法:

题意有点绕,意思是是给你一个字符串,和一个字符串的数组,需要返回一个该字符串的索引组成的数组,其中字符串数组中各成员长度要求一致,返回的索引有如下性质:

从每个索引开始,长度为L的字串需要精确包含字符串数组中的所有字符串(不多不少)。L 为字符串数组中所有字符串长度之和。

思路是:先用一个Map结构,记录字符串数组中各个字符串出现的个数,用于之后判断子串中各字符串是否出现够数,之后,从头开始遍历字符串,找和字符串数组中的字符串相同的字串,找到后map中的值减一,否则重新初始化map,从下一个字符开始遍历。如果map中所有的值都为0,则找到了一个符合条件的子串,索引压入数组。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
Map<String, Integer> wordcount = new HashMap<String, Integer>();
List<Integer> result = new ArrayList<Integer>();
if(s == "" || words.length == 0){
return result;
}
int wordlen = words[0].length();
int word_count = words.length;
for (String word : words) {
if(word.length()!=wordlen){
return result;
}
if (!wordcount.containsKey(word)) {
wordcount.put(word, 1);
} else {
wordcount.put(word, wordcount.get(word) + 1);
}
}

for (int i = 0; i <= s.length() - wordlen; i++) {
String tmpsub = s.substring(i, i + wordlen);
Map<String, Integer> tmpmap = new HashMap<>();
tmpmap.putAll(wordcount);
if (!tmpmap.containsKey(tmpsub)) {
continue;
} else {
int remain_word_count = word_count;
int j = i;
while (remain_word_count > 0) {
if (tmpmap.get(tmpsub) > 0) {
tmpmap.put(tmpsub, tmpmap.get(tmpsub) - 1);
j += wordlen;
remain_word_count -= 1;
if(j>s.length() - wordlen){
break;
}
tmpsub = s.substring(j, j + wordlen);
if (!tmpmap.containsKey(tmpsub)){
break;
}
} else {
break;
}
}
if(remain_word_count == 0){
result.add(i);
}

}
}
return result;
}
}