一、问题描述
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]
.
二、解题思路
将words中的短字符串按照不同的顺序组合成一条长字符串(words中的每个字符串必须出现,且仅能出现一次),寻找该字符串在s中的起始位置。思路是参考http://blog.csdn.net/linhuanmars/article/details/20342851的思路。构建一个HashMap(变量名是map),键是words中的字符串,值是该字符串在words中出现的次数;主要思路在字符串s维护一个窗口,如果当前截取的字符串在s中,则继续移动右窗口;如果不在,则将左窗口右移。假设字符串s的长度是N,列表中字符串的长度是L,则 i 从0到L-1开始,得到开始index分别为i,i+1,...i+L-1的长字符串,并且每次循环开始的窗口左端也等于这些index。并构建临时HashMap(变量名是curmap),截取s中的字符串str后判断该字符串是否在map里,如果出现在map里,则在curmap中记录该字符出现的次数。
三、代码
public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
ArrayList<Integer> res=new ArrayList<Integer>();
if(s==null || s.length()==0 || words==null || words.length==0)
return res;
//构建map
HashMap<String,Integer> map=new HashMap<String,Integer>();
for(int i=0;i<words.length;i++){
if(map.containsKey(words[i]))
map.put(words[i],map.get(words[i])+1);
else
map.put(words[i],1);
}
for(int i=0;i<words[0].length();i++){
HashMap<String,Integer> curmap=new HashMap<String,Integer>();
int count=0;
int left=i;//窗口左端
for(int j=i;j<=s.length()-words[0].length();j+=words[0].length()){
String str=s.substring(j,j+words[0].length());
if(map.containsKey(str)){
if(curmap.containsKey(str))
curmap.put(str,curmap.get(str)+1);
else
curmap.put(str,1);
if(curmap.get(str)<=map.get(str)){
count++;
}else{
while(curmap.get(str)>map.get(str)){
String temp=s.substring(left,left+words[0].length());
if(curmap.containsKey(temp))
curmap.put(temp,curmap.get(temp)-1);
if(curmap.get(temp)<map.get(temp))
count--;//if语句是确保为该字符串执行过count++,没有执行的则不用--
left+=words[0].length();
}
}
if(count==words.length){
res.add(left);
String temp=s.substring(left,left+words[0].length());
curmap.put(temp,curmap.get(temp)-1);
count--;
left+=words[0].length();
}
}
else{
curmap.clear();
count=0;
left=j+words[0].length();
}
}
}
return res;
}
}