forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path30_findSubstring.java
30 lines (29 loc) · 1.19 KB
/
30_findSubstring.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<Integer>();
int num = words.length;
int len = words[0].length();
if(s == null || s.length() < num*len) return res;
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(String word: words){
if(map.containsKey(word)) map.put(word, map.get(word)+1);
else map.put(word, 1);
}
for(int i = 0; i <= s.length() - num*len; i++){ //Attemtion: this is <= not <
HashMap<String, Integer> copy = new HashMap<>(map);//Need a copy!!!!
for(int k = 0; k < num; k++){
String str = s.substring(i+k*len, i+k*len+len);
if(copy.containsKey(str)){
if(copy.get(str) == 0) break;
else if(copy.get(str) == 1) copy.remove(str);
else copy.put(str, copy.get(str)-1);
if(copy.isEmpty()){
res.add(i);
break;//need this break!
}
} else break;
}
}
return res;
}
}