-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathSubstring with Concatenation of All Words.java
53 lines (52 loc) · 2.01 KB
/
Substring with Concatenation of All Words.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
int numberOfWords = words.length;
int singleWordLength = words[0].length();
int totalSubstringLength = singleWordLength * numberOfWords;
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
List<Integer> result = new ArrayList<>();
for (int i = 0; i < singleWordLength; i++) {
slidingWindow(i, s, result, singleWordLength, totalSubstringLength, wordCount, numberOfWords);
}
return result;
}
private void slidingWindow(int left, String s, List<Integer> answer, int singleWordLength,
int totalSubstringLength, Map<String, Integer> wordCount, int numberOfWords) {
Map<String, Integer> wordsFound = new HashMap<>();
int wordsUsed = 0;
boolean excessWord = false;
int n = s.length();
for (int right = left; right <= n - singleWordLength; right += singleWordLength) {
String currSubstring = s.substring(right, right + singleWordLength);
if (!wordCount.containsKey(currSubstring)) {
wordsFound.clear();
wordsUsed = 0;
excessWord = false;
left = right + singleWordLength;
} else {
while (right - left == totalSubstringLength || excessWord) {
String leftmostWord = s.substring(left, left + singleWordLength);
left += singleWordLength;
wordsFound.put(leftmostWord, wordsFound.get(leftmostWord) - 1);
if (wordsFound.get(leftmostWord) >= wordCount.get(leftmostWord)) {
excessWord = false;
} else {
wordsUsed--;
}
}
wordsFound.put(currSubstring, wordsFound.getOrDefault(currSubstring, 0) + 1);
if (wordsFound.get(currSubstring) <= wordCount.get(currSubstring)) {
wordsUsed++;
} else {
excessWord = true;
}
if (wordsUsed == numberOfWords && !excessWord) {
answer.add(left);
}
}
}
}
}