-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path30. Substring with Concatenation of All Words.java
52 lines (42 loc) · 1.34 KB
/
30. 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
class Solution {
HashMap<String, Integer> h = new HashMap<>();
int wordsLen;
int wordLen;
int k;
public boolean check(int idx, String s) {
int c = 0;
HashMap<String, Integer> h1 = new HashMap<>(h);
for (int i = idx; i < idx + k; i += wordLen) {
String str = s.substring(i, i + wordLen);
if (h1.containsKey(str)) {
if (h1.get(str) > 0) {
c++;
h1.put(str, h1.get(str) - 1);
if (c == wordsLen) {
return true;
}
} else {
break;
}
} else {
break;
}
}
return c == wordsLen;
}
public List<Integer> findSubstring(String s, String[] words) {
for (int i = 0; i < words.length; i++) {
h.put(words[i], h.getOrDefault(words[i], 0) + 1);
}
wordsLen = words.length;
wordLen = words[0].length();
k = wordsLen * wordLen;
List<Integer> arr = new ArrayList<>();
for (int i = 0; i <= s.length() - k; i++) {
if (check(i, s)) {
arr.add(i);
}
}
return arr;
}
}