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.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
由于L中字符串长度一致,可以使用substring方法提取子串,判断L中是否存在,循环n次
public class Solution {
public List<Integer> findSubstring(String S, String[] L) {
ArrayList<Integer>res=new ArrayList<Integer>();
HashMap<String,Integer>words=new HashMap<String,Integer>();
HashMap<String,Integer>now=new HashMap<String,Integer>();
int n=L.length;
int tmp;
if(n==0)
return res;
for(int i=0;i<n;i++){
if(words.containsKey(L[i])){
tmp=words.get(L[i]);
tmp++;
words.put(L[i], tmp);
}
else
words.put(L[i], 1);
}
int len=L[0].length();
int l=S.length();
for(int i=0;i<=l-n*len;i++){
now.clear();
int j;
for(j=0;j<n;j++){ //n次循环判断
String word=S.substring(i+j*len, i+j*len+len); //截取子串
if(words.containsKey(word)){ //是否包含
if(now.containsKey(word)){
tmp=now.get(word);
tmp++;
now.put(word, tmp);
}
else
now.put(word, 1);
if(now.get(word)>words.get(word)) //判断次数是否超过
break;
}
else break;
}
if(j==n)
res.add(i);
}
return res;
}
}