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) ins 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).
这道题目主要是运用滑动窗口的思想。
首先设置一个Map<String,int> (记作need)记录words中所有的字符串,Map<String,int> (记作has)则表示当前遍历的情况。
设words中的任一一个字符串的长度为len,则i从0到len,对于每个i,分别看s在[i,i+len] ,[i+len,i+2*len]........的子串,是否符合要求,符合要求就添加到has中。
内层循环的时间复杂度为O(n/len),外层循环的时间复杂度为O(len),所以总的时间复杂度为O(n)。
代码如下:
public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<Integer>();
if(s == null || s.length() == 0 || words == null || words.length == 0)
return res;
HashMap<String, Integer> need = new HashMap<String, Integer>();
HashMap<String, Integer> has = new HashMap<String, Integer>();
for(int i = 0; i < words.length; i ++){
if(need.containsKey(words[i]))
need.put(words[i], need.get(words[i])+1);
else
need.put(words[i],1);
}
int len = words[0].length();
for(int i = 0; i < len ; i++){
int start = i;
int cur = i;
while(start <= s.length() - words.length *len && cur <= s.length() -len){
String str = s.substring(cur,cur+len);
if(need.containsKey(str)){
if(has.containsKey(str) && has.get(str) == need.get(str)){
String tmp = s.substring(start,start+len);
has.put(tmp, has.get(tmp)-1);
start += len;
continue;
}
else if(!has.containsKey(str)){
has.put(str, 1);
}
else{
has.put(str, has.get(str)+1);
}
cur += len;
if(cur - start == words.length*len){
res.add(start);
String tmp = s.substring(start,start+len);
has.put(tmp, has.get(tmp)-1);
start += len;
}
}
else{
has.clear();
cur += len;
start = cur;
}
}
has.clear();
}
return res;
}
}