1
+ // Runtime: 68 ms (Top 73.46%) | Memory: 43.2 MB (Top 88.65%)
1
2
class Solution {
2
3
public List <Integer > findSubstring (String s , String [] words ) {
3
-
4
+
4
5
HashMap <String , Integer > input = new HashMap <>();
5
6
int ID = 1 ;
6
7
HashMap <Integer , Integer > count = new HashMap <>();
@@ -9,17 +10,17 @@ public List<Integer> findSubstring(String s, String[] words) {
9
10
input .put (word , ID ++);
10
11
int id = input .get (word );
11
12
count .put (id ,count .getOrDefault (id ,0 )+1 );
12
-
13
+
13
14
}
14
15
int len = s .length ();
15
16
int wordLen = words [0 ].length ();
16
17
int numWords = words .length ;
17
18
int windowLen = wordLen *numWords ;
18
19
int lastIndex = s .length ()-windowLen ;
19
-
20
+
20
21
int curWordId [] = new int [len ];
21
22
String cur = " " +s .substring (0 ,wordLen -1 );
22
-
23
+
23
24
//Change to int array
24
25
for (int i = 0 ; i < (len -wordLen +1 ); i ++) {
25
26
cur = cur .substring (1 , cur .length ())+s .charAt (i +wordLen -1 );
@@ -30,32 +31,31 @@ public List<Integer> findSubstring(String s, String[] words) {
30
31
}
31
32
}
32
33
List <Integer > res = new ArrayList <>();
33
-
34
+
34
35
//compare using int make it faster 30 times in each comparison
35
36
for (int i = 0 ; i <= lastIndex ; i ++) {
36
-
37
+
37
38
HashMap <Integer , Integer > winMap = new HashMap <>();
38
39
for (int j = 0 ; j < windowLen && curWordId [i ] != -1 ; j +=wordLen ) {
39
-
40
+
40
41
int candidate = curWordId [j +i ];
41
-
42
+
42
43
if (!count .containsKey (candidate ))
43
44
break ;
44
45
else {
45
46
winMap .put (candidate , winMap .getOrDefault (candidate , 0 )+1 );
46
47
}
47
48
if (winMap .get (candidate ) > count .get (candidate ))
48
49
break ;
49
-
50
-
50
+
51
51
if (j == (windowLen - wordLen ) && winMap .size () == count .size ()){
52
52
res .add (i );
53
-
53
+
54
54
}
55
-
55
+
56
56
}
57
57
}
58
-
58
+
59
59
return res ;
60
60
}
61
- }
61
+ }
0 commit comments