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 shoshould return the indices:[0,9]
.
(Order does not matter ).
Algorithm ideas:
1. traverse S, get the length of wordlength every time a character is encountered, and verify whether it is in L, if not, I ++, such as, loop iteration, until a concatenation (recorded) or mismatch is found. Continue with I ++. The best time complexity is O (n), and the worst is O (n * num * wordlength)
1 public class Solution { 2 List<Integer> list = new ArrayList<Integer>(); 3 public List<Integer> findSubstring(String S, String[] L) { 4 int num = L.length; 5 int wordLength = L[0].length(); 6 if(S.length() < wordLength * num) return list; 7 HashMap<String,Integer> hash = new HashMap<String,Integer>(); 8 for(int i = 0; i < L.length; i++){ 9 if(hash.containsKey(L[i])) hash.put(L[i],hash.get(L[i]) + 1);10 else hash.put(L[i],1);11 }12 HashMap<String,Integer> copy = new HashMap<String,Integer>(hash);13 for(int i = 0; i <= S.length() - wordLength; i++){14 int start = i;15 int end = start + wordLength;16 String sub = S.substring(start, end); 17 if(copy.get(sub)!=null && copy.get(sub) != 0){18 int count = 0;19 boolean canLoop = true;20 while(canLoop){21 copy.put(S.substring(start, end), copy.get(S.substring(start, end)) - 1);22 count++;23 if(count == num){24 list.add(i);25 copy = (HashMap<String,Integer>)hash.clone();26 break;27 }28 start = end;29 end += wordLength;30 if(end > S.length() || !copy.containsKey(S.substring(start, end)) || copy.get(S.subSequence(start, end).toString()) <= 0){31 canLoop = false;32 copy = (HashMap<String,Integer>)hash.clone();33 }34 }35 }36 }37 return list;38 }39 }
Idea 2:
Optimization, double pointer method, similar to longest substring without repeating characters, the complexity can reach linear. (To be verified)
Reference link:
Http://blog.csdn.net/ojshilu/article/details/22212703
Http://blog.csdn.net/linhuanmars/article/details/20342851