- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem30.java
More file actions
Latest commit
74 lines (63 loc) · 2.07 KB
/
Copy pathProblem30.java
File metadata and controls
74 lines (63 loc) · 2.07 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
importjava.util.*;
classProblem30 {
publicstaticvoidmain(String[] args) {
String[] words = newString[]{"foo", "bar"};
Strings = "barfoothefoobarman";
System.out.print(newProblem30().findSubstring(s, words));
}
publicList<Integer> findSubstring(Strings, String[] words) {
// 将words全排列,找到所有和新排列匹配的对象,时间复杂度为K!
// request length of total words as substring, and compare with s.
List<Integer> res = newArrayList<>();
// edge
if (s.length() <= 0 || words.length <= 0 || words[0].length() <= 0) {
returnres;
}
// slide model
intsize = words.length * words[0].length(); // minimal pattern length;
intlen = words[0].length();
//
HashMap<String, Integer> hashMap = newHashMap<>();
for (Stringword : words) {
if (hashMap.containsKey(word)) hashMap.put(word, hashMap.get(word) + 1);
elsehashMap.put(word, 1);
}
inttmp = -1;
for (intpos = 0; pos < s.length() - size + 1; pos++) {
StringtStr = s.substring(pos, len+pos);
if (hashMap.containsKey(tStr)) {
intt = hashMap.get(tStr)-1;
hashMap.put(tStr, t);
} elseif (checkMap(hashMap)) {
pos--;
res.add(pos+len-size);
resetMap(hashMap);
}
}
returnres;
}
booleancheckMap(HashMap<String, Integer> hashMap) {
// check if all value is 0
booleanflag = true;
Iteratoriter = hashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Integer> entry = (Map.Entry) iter.next();
Stringkey = entry.getKey();
Integerval = entry.getValue();
if (val != 0) {
flag = false;
returnflag;
}
}
returnflag;
}
voidresetMap(HashMap<String, Integer> hashMap) {
// reset all value to 1
Iteratoriter = hashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Integer> entry = (Map.Entry) iter.next();
Stringkey = entry.getKey();
hashMap.put(key, 1);
}
}
}