標籤:style blog color strong io art for re
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).
題解:題目的意思是在S中找到一個子串,恰好包含了L中所有的串,L中的串在S的字串中的順序不重要。
思路很簡單,假設L中共有m個串,每個串長度為n,那麼L中子串合并起來總長度是m*n,那麼只要在S中依次搜尋長度為m*n的串就可以了。在搜尋的過程中,設定兩個hashmap,一個存放L中的串和它們在L中出現的次數,一個存放在S中m*n的子串中找到的長度為n的串和它們在S的子串中出現的次數,因為查看的是S長度為m*n的子串,並且是n個字元為一組查看的,所以要麼在S中看到某個長度為n的子串不出現在L中,要麼在S中出現的次數比L中多,否則這個長度為m*n的串就是L的所有串的合并。
例如題目中的例子
- 我們首先查看S的子串barfoo,查看這個子串的時候,按照bar,foo的順序查看,得知子串foobar是符合要求的
- 再查看子串arfoot,查看順序是arf,oot,發現arf不在L中,所以arfoot不符合要求;
- 再查看子串rfooth,......
1 if(L == null || L.length == 0) 2 return null; 3 int m = L.length; 4 int n = L[0].length(); 5 //store n-length strings in L 6 HashMap<String, Integer> map = new HashMap<String, Integer>(); 7 //store n-length strings inS 8 HashMap<String, Integer> InS = new HashMap<String, Integer>(); 9 List<Integer> answer = new ArrayList<Integer>();10 for(String s:L){11 if(!map.containsKey(s))12 map.put(s, 1);13 else {14 map.put(s, map.get(s)+1);15 }16 }17 18 19 for(int i = 0;i <= S.length() - m*n;i++){20 InS.clear();21 boolean find = true;22 for(int j = 0;j < m;j++){23 String sub = S.substring(i+j*n,i+(j+1)*n);24 //if a n-length string in S‘s substring doesn‘t in L, skip to search a new substring in S25 if(!map.containsKey(sub)){26 find = false;27 break;28 }29 if(!InS.containsKey(sub))30 InS.put(sub, 1);31 else {32 InS.put(sub, InS.get(sub)+1);33 }34 //if a n-length string in S‘substring appears more time than in L, stop checking this substring35 if(InS.get(sub) > map.get(sub)){36 find = false;37 break;38 }39 }40 if(find)41 answer.add(i);42 }43 return answer;