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]
.
(order does not matter).
本题很难,先说思路,首先要把words存放在hashmap里面,key存放String,value存放出现个数。因为words的string长度是一样的,假设长度为len,遍历s的时候只要在[0,len-1] 为开始点,然后每次加上len长度就可以了。同时还需要设置一个counter的长度,用来比较是否和words的长度相等。接下来再做一个hashmap,用来存储每次遍历的len长度的string,如果在words的hashmap里面出现了,则长度+1,否则清零。
1 public class Solution { 2 public List<Integer> findSubstring(String s, String[] words) { 3 List<Integer> res = new ArrayList<Integer>(); 4 Map<String,Integer> map = new HashMap<>(); 5 int len = words[0].length(); 6 if(s.length()==0||words.length==0) return res; 7 for(String word:words){ 8 map.put(word,map.getOrDefault(word,0)+1); 9 } 10 for(int i=0;i<len;i++){ 11 int left = i; 12 int counter = 0; 13 Map<String,Integer> smap = new HashMap<>(); 14 for(int j=i;j<=s.length()-len;j+=len){ 15 String str = s.substring(j,j+len); 16 if(map.containsKey(str)){ 17 smap.put(str,smap.getOrDefault(str,0)+1); 18 if(smap.get(str)<=map.get(str)){ 19 counter++; 20 }else{ 21 while(smap.get(str)>map.get(str)){ 22 String sstr = s.substring(left,left+len); 23 smap.put(sstr,smap.get(sstr)-1); 24 if(smap.get(sstr)<map.get(sstr)) counter--; 25 left+=len; 26 } 27 } 28 if(counter==words.length){ 29 System.out.println(left); 30 res.add(left); 31 counter--; 32 String sstr = s.substring(left,left+len); 33 smap.put(sstr,smap.get(sstr)-1); 34 left = left+len; 35 } 36 }else{ 37 counter = 0; 38 left = j+len; 39 smap.clear(); 40 } 41 } 42 } 43 return res; 44 } 45 }