Substring with Concatenation of All Words
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).
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public ArrayList<Integer> findSubstring(String S, String[] L) { 3 ArrayList<Integer> res = new ArrayList<Integer> (); 4 int len1 = S.length(); 5 int len2 = L.length; 6 if(len2<=0||len1<=0) return res; 7 int wordLen = L[0].length(); 8 HashMap<String,Integer> ex = new HashMap<String,Integer>(); 9 HashMap<String,Integer> app = new HashMap<String,Integer>(); 10 for(int i=0;i<len2;i++){ 11 if(ex.get(L[i])==null) { 12 ex.put(L[i],1); 13 app.put(L[i],0); 14 } 15 else ex.put(L[i],ex.get(L[i])+1); 16 } 17 for(int i=0;i<=len1-len2*wordLen;i++){ 18 int start = i; 19 String temp = S.substring(start,start+wordLen); 20 while(ex.get(temp)!=null && ex.get(temp)>app.get(temp)){ 21 app.put(temp,app.get(temp)+1); 22 start +=wordLen; 23 if(start+wordLen>len1)break; 24 temp = S.substring(start,start+wordLen); 25 } 26 if(start-i==wordLen*len2) 27 res.add(i); 28 for(int j=0;j<len2;j++){ 29 app.put(L[j],0); 30 } 31 } 32 return res; 33 } 34 }