题目描述:
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.i
For example, given:
S:"barfoothefoobarman"
L:["foo", "bar"]
You should return the indices:[0,9].
(order does not matter).
思路解析:
代码:
import java.util.*;
public class Solution {
public ArrayList findSubstring(String S, String[] L) {
ArrayList res = new ArrayList();
if(S==null||L==null||S.length()==0||L.length==0)
return res;
HashMap dict = new HashMap();
int len = L[0].length();
for(String word :L){
if(!dict.containsKey(word))
dict.put(word,1);
else
dict.put(word,dict.get(word)+1);
}
for(int i=0;i cur = new HashMap();
int count =0;
int index = i;
for(int j=i;j<=S.length()-len;j+=len){
String curword = S.substring(j,j+len);
if(!dict.containsKey(curword)){
cur.clear();
count =0;
index = j+len;
}else{
if(!cur.containsKey(curword)){
cur.put(curword,1);
}else{
cur.put(curword,cur.get(curword)+1);
}
if(cur.get(curword)<=dict.get(curword)){
count++;
}else{
String temp = S.substring(index,index+len);
cur.put(temp,cur.get(temp)-1);
index = index+len;
}
if(count==L.length){
res.add(index);
String temp = S.substring(index,index+len);
cur.put(temp,cur.get(temp)-1);
index = index +len;
count--;
}
}
}
}
Collections.sort(res);
return res;
}
}