问题描述
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.
For example, given:
s: “barfoothefoobarman”
words: [“foo”, “bar”]
You should return the indices: [0,9].
(order does not matter).
思考:问题类似与Longest Substring Without Repeating Characters 和Minimum Window Substring
想法
- 1、维护一个dictmap,保存words的单词以及个数,map保存s的字串(已经遍历的并且带验证的)。设total为单词总数。
- 2、维护两个index:left(start index)和j(当前index),设置一个count保存当前已加入map的单词数。
- 3、从j出去字串(长度为len)str,如果dict中包含str,则将str加入map,并且count++,此时,如果map中str的value大于dict中str的value,则需要将left后移(即left 到j+len , 这段序列包含太多单词,需要删除),这个过程需要涉及count的变化。
- 4、如果count == total,则表示map与dict,重的值相同,即找到一个start index,在结果链表中加入left。
- 5、将left + len,继续循环;
代码:
public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
int n = s.length();
int total = words.length;
List<Integer> ret = new LinkedList<>();
if (n <= 0 || total <= 0) return ret;
Map<String,Integer> dict = new HashMap<>();
for(String word:words){
Integer value = dict.get(word);
if(value == null)
dict.put(word,1);
else
dict.put(word,value + 1);
}
int len = words[0].length();
for(int i = 0; i < len; i++){
Map<String,Integer> subStr = new HashMap<>();
int left = i;
int count = 0;
String start = null;
for(int j = i; j <= n - len; j += len){
String temp = s.substring(j,j + len);
Integer num = dict.get(temp);
if(num != null){
Integer value = subStr.get(temp);
if (value == null)
value = 1;
else value += 1;
subStr.put(temp,value);
if(value <= num)
count++;
else
while(subStr.get(temp) > dict.get(temp)){
String str = s.substring(left, left + len);
Integer valueStr = subStr.get(str);
if(--valueStr < dict.get(str)) count--;
subStr.put(str,valueStr);
left += len;
}
if(count == total){
ret.add(left);
count--;
String str = s.substring(left,left + len);
subStr.put(str,subStr.get(str) - 1);
left += len;
}
}
else {
left = j + len;
count = 0;
subStr.clear();
}
}
}
return ret;
}
}