-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSliding.java
More file actions
66 lines (51 loc) · 2.07 KB
/
Copy pathSliding.java
File metadata and controls
66 lines (51 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
import java.util.*;
import java.util.Map;
class Sliding {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> result = new ArrayList<>();
if (s == null || words.length == 0) return result;
int wordLen = words[0].length();
int wordCount = words.length;
int totalLen = wordLen * wordCount;
Map<String, Integer> wordMap = new HashMap<>();
for (String word : words) {
wordMap.put(word, wordMap.getOrDefault(word, 0) + 1);
}
for (int i = 0; i < wordLen; i++) {
int left = i, count = 0;
Map<String, Integer> windowMap = new HashMap<>();
for (int j = i; j + wordLen <= s.length(); j += wordLen) {
String word = s.substring(j, j + wordLen);
if (wordMap.containsKey(word)) {
windowMap.put(word, windowMap.getOrDefault(word, 0) + 1);
count++;
while (windowMap.get(word) > wordMap.get(word)) {
String leftWord = s.substring(left, left + wordLen);
windowMap.put(leftWord, windowMap.get(leftWord) - 1);
left += wordLen;
count--;
}
if (count == wordCount) {
result.add(left);
String leftWord = s.substring(left, left + wordLen);
windowMap.put(leftWord, windowMap.get(leftWord) - 1);
left += wordLen;
count--;
}
} else {
windowMap.clear();
count = 0;
left = j + wordLen;
}
}
}
return result;
}
public static void main(String[] args){
String s = "barfoothefoobarman";
String[] words = {"foo", "bar"};
Sliding obj = new Sliding();
List<Integer> ans = obj.findSubstring(s, words); // correct call
System.out.println(ans);
}
}