-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.php
60 lines (52 loc) · 1.35 KB
/
Solution.php
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
class Solution {
/**
* @param String $s
* @param String[] $words
* @return Integer[]
*/
function findSubstring($s, $words) {
$cnt = [];
foreach ($words as $w) {
if (isset($cnt[$w])) {
$cnt[$w]++;
} else {
$cnt[$w] = 1;
}
}
$ans = [];
$m = strlen($s);
$n = count($words);
$k = strlen($words[0]);
for ($i = 0; $i < $k; $i++) {
$l = $i;
$r = $i;
$cnt1 = [];
while ($r + $k <= $m) {
$t = substr($s, $r, $k);
$r += $k;
if (!isset($cnt[$t])) {
$cnt1 = [];
$l = $r;
continue;
}
if (isset($cnt1[$t])) {
$cnt1[$t]++;
} else {
$cnt1[$t] = 1;
}
while ($cnt1[$t] > $cnt[$t]) {
$w = substr($s, $l, $k);
$cnt1[$w]--;
if ($cnt1[$w] == 0) {
unset($cnt1[$w]);
}
$l += $k;
}
if ($r - $l == $n * $k) {
$ans[] = $l;
}
}
}
return $ans;
}
}