【题目】
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).
【思路】
采用滑动窗口机制进行解题,设数组的长度为length,单词的长度为distance
首先维护一个单次字典,用map实现,键为数组中的单词,值为数组中单词出现的次数,若滑动窗口中出现相应的字符串,则对应的值减去1;
滑动窗口的初始大小为0,窗口的左边界不变,右边界向右滑动distance个单位,若当前窗口中新增加的字符串出现在字典中,且值>0, 继续向右滑动distance个单位,若值=0,或者没有出现在字典中,则左窗口向右滑动一个单位,窗口大小重新变为0 ,初始化字典。
若当前窗口中的字符串长度 = length*distance,则表示找到了一个正确的字符串,将窗口的左下标存入结果中,左窗口向右滑动一个单位,窗口大小重新变为0,初始化字典。
【Java代码】
public class Solution {
public List<Integer> findSubstring(String s, String[] words){
List<Integer> result = new ArrayList<Integer>();
if(s == "" || words.length == 0)
return null;
else{
int distance = words[0].length();
int length = words.length;
HashMap<String,Integer> dict_org = initDict(words);
HashMap<String,Integer> dict = new HashMap<String,Integer>();
dict.putAll(dict_org);
for(int i = 0 ; i <= s.length() - distance * length ;){
boolean change_flag = false;
int curr_distance = 0; //滑动窗口的大小
String curr = s.substring(i+curr_distance,i+curr_distance+distance);
while(dict.containsKey(curr) && dict.get(curr) > 0){
curr_distance += distance;
dict.put(curr, dict.get(curr)-1);
change_flag = true;
if(curr_distance == distance * length){ //找到一个subString
result.add(i);
break;
}
curr = s.substring(i+curr_distance,i+curr_distance+distance);
}
if(change_flag){
dict.putAll(dict_org);
}
i += 1;
}
return result;
}
}
public HashMap<String,Integer> initDict(String[] w){
HashMap<String, Integer> dict = new HashMap<String,Integer>();
for(int i = 0 ; i < w.length ; i++){
if(dict.containsKey(w[i]))
dict.put(w[i], dict.get(w[i])+1);
else
dict.put(w[i],1);
}
return dict;
}
}
【改进空间】
由于特殊情况的存在,例如:
1、s = "wordgoodbestwordgoodbest", words = {"word","good","best"} 使得左窗口向右一次性滑动的最大距离为distance
2、s = "cccca", words = {"cc","ca"},使得左窗口向右一次性滑动的最大距离又缩短为1
导致上述思路中,左窗口只能以1为单位向右滑动,虽然没有超时,但明显会对运行时间造成很大的影响,希望有后续算法可以改进