1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace leetcode; |
||
6 | |||
7 | class WordBreak |
||
8 | { |
||
9 | public static function wordBreak(string $s, array $words): bool |
||
10 | { |
||
11 | if (strlen($s) <= 0 || count($words) <= 0) { |
||
12 | return false; |
||
13 | } |
||
14 | $dicts = array_flip(array_unique(array_values($words))); |
||
15 | $memo = array_fill(0, strlen($s), -1); |
||
16 | |||
17 | return self::helper($s, $dicts, 0, $memo); |
||
18 | } |
||
19 | |||
20 | private static function helper( |
||
21 | string $s, |
||
22 | array &$dicts, |
||
23 | int $start, |
||
24 | array &$memo |
||
25 | ): bool { |
||
26 | $n = strlen($s); |
||
27 | if ($start >= $n) { |
||
28 | return true; |
||
29 | } |
||
30 | if (isset($memo[$start]) && $memo[$start] !== -1) { |
||
31 | return (bool) $memo[$start]; |
||
32 | } |
||
33 | for ($i = $start; $i <= $n; $i++) { |
||
34 | $key = substr($s, $start, $i - $start); |
||
35 | if (isset($dicts[$key]) && self::helper($s, $dicts, $i, $memo)) { |
||
36 | return (bool) ($memo[$start] = 1); |
||
37 | } |
||
38 | } |
||
39 | |||
40 | return (bool) ($memo[$start] = 0); |
||
41 | } |
||
42 | |||
43 | public static function wordBreak2(string $s, array $words) |
||
44 | { |
||
45 | if (strlen($s) <= 0 || count($words) <= 0) { |
||
46 | return false; |
||
47 | } |
||
48 | $dicts = array_flip(array_unique(array_values($words))); |
||
49 | $dp = array_fill(0, strlen($s) + 1, false); |
||
50 | [$dp[0], $n] = [true, count($dp)]; |
||
51 | for ($i = 0; $i < $n; $i++) { |
||
52 | for ($j = 0; $j < $i; $j++) { |
||
53 | $key = substr($s, $j, $i - $j); |
||
54 | if (isset($dicts[$key]) && $dp[$j]) { |
||
55 | $dp[$i] = true; |
||
56 | break; |
||
57 | } |
||
58 | } |
||
59 | } |
||
60 | |||
61 | return array_pop($dp); |
||
62 | } |
||
63 | |||
64 | public static function wordBreak3(string $s, array $words): bool |
||
65 | { |
||
66 | $n = strlen($s); |
||
67 | if ($n <= 0 || count($words) <= 0) { |
||
68 | return false; |
||
69 | } |
||
70 | $dicts = array_flip(array_unique(array_values($words))); |
||
71 | $visited = array_fill(0, $n, false); |
||
72 | $queue = [0]; |
||
73 | while ($queue) { |
||
0 ignored issues
–
show
|
|||
74 | $start = $queue[0]; |
||
75 | array_pop($queue); |
||
76 | if (!$visited[$start]) { |
||
77 | for ($i = $start + 1; $i <= $n; $i++) { |
||
78 | $key = substr($s, $start, $i - $start); |
||
79 | if (isset($dicts[$key])) { |
||
80 | $queue[] = $i; |
||
81 | if ($i === $n) { |
||
82 | return true; |
||
83 | } |
||
84 | } |
||
85 | } |
||
86 | $visited[$start] = true; |
||
87 | } |
||
88 | } |
||
89 | |||
90 | return false; |
||
91 | } |
||
92 | } |
||
93 |
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.