1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace leetcode; |
6
|
|
|
|
7
|
|
|
class BackspaceStringCompare |
8
|
|
|
{ |
9
|
|
|
public static function backspaceCompare(string $s, string $t): bool |
10
|
|
|
{ |
11
|
|
|
if (empty($s) || empty($t)) { |
12
|
|
|
return false; |
13
|
|
|
} |
14
|
|
|
$helper = static function (string &$s, int &$i) { |
15
|
|
|
$n = 0; |
16
|
|
|
while ($i >= 0 && ($n > 0 || $s[$i] === '#')) { |
17
|
|
|
$n = $s[$i] === '#' ? $n + 1 : $n - 1; |
18
|
|
|
$i--; |
19
|
|
|
} |
20
|
|
|
return $i >= 0 ? $s[$i] : '#'; |
21
|
|
|
}; |
22
|
|
|
[$i, $j] = [strlen($s) - 1, strlen($t) - 1]; |
23
|
|
|
while ($i >= 0 || $j >= 0) { |
24
|
|
|
$p = $helper($s, $i); |
25
|
|
|
$q = $helper($t, $j); |
26
|
|
|
if ($p !== $q) { |
27
|
|
|
return false; |
28
|
|
|
} |
29
|
|
|
$i--; |
30
|
|
|
$j--; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
return true; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public static function backspaceCompare2(string $s, string $t): bool |
37
|
|
|
{ |
38
|
|
|
if (empty($s) || empty($t)) { |
39
|
|
|
return false; |
40
|
|
|
} |
41
|
|
|
[$i, $j] = [strlen($s) - 1, strlen($t) - 1]; |
42
|
|
|
$m = $n = 0; |
43
|
|
|
while (true) { |
44
|
|
|
while ($i >= 0 && ($m > 0 || $s[$i] === '#')) { |
45
|
|
|
$m += $s[$i] === '#' ? 1 : -1; |
46
|
|
|
$i--; |
47
|
|
|
} |
48
|
|
|
while ($j >= 0 && ($n > 0 || $t[$j] === '#')) { |
49
|
|
|
$n += $t[$j] === '#' ? 1 : -1; |
50
|
|
|
$j--; |
51
|
|
|
} |
52
|
|
|
if ($i >= 0 && $j >= 0 && $s[$i] === $t[$j]) { |
53
|
|
|
$i--; |
54
|
|
|
$j--; |
55
|
|
|
} else { |
56
|
|
|
break; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return $i === -1 && $j === -1; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public static function backspaceCompare3(string $s, string $t): bool |
64
|
|
|
{ |
65
|
|
|
if (empty($s) || empty($t)) { |
66
|
|
|
return false; |
67
|
|
|
} |
68
|
|
|
$helper = static function (string $s, array $stack) { |
69
|
|
|
$n = strlen($s); |
70
|
|
|
for ($i = 0; $i < $n; $i++) { |
71
|
|
|
if ($s[$i] === '#') { |
72
|
|
|
if (!$stack) { |
|
|
|
|
73
|
|
|
continue; |
74
|
|
|
} |
75
|
|
|
array_pop($stack); |
76
|
|
|
} else { |
77
|
|
|
array_push($stack, $s[$i]); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
return $stack; |
81
|
|
|
}; |
82
|
|
|
[$p, $q] = [$helper($s, []), $helper($t, [])]; |
83
|
|
|
|
84
|
|
|
return $p === $q; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|
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.