IsSubsequence::isSubsequence2()   B
last analyzed

Complexity

Conditions 8
Paths 17

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 16
c 2
b 0
f 0
dl 0
loc 27
rs 8.4444
cc 8
nc 17
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class IsSubsequence
8
{
9
    public static function isSubsequence(string $s, string $t): bool
10
    {
11
        [$m, $n, $i, $j] = [strlen($s), strlen($t), 0, 0];
12
        if ($m < 0 || $n < 0) {
13
            return false;
14
        }
15
        while ($i < $m && $j < $n) {
16
            if ($s[$i] === $t[$j]) {
17
                $i++;
18
            }
19
            $j++;
20
        }
21
22
        return $i === $m;
23
    }
24
25
    public static function isSubsequence2(string $s, string $t): bool
26
    {
27
        [$m, $n] = [strlen($s), strlen($t)];
28
        if ($m < 0 || $n < 0) {
29
            return false;
30
        }
31
32
        $dp = array_fill(0, $m + 1, array_fill(0, $n + 1, false));
33
        $dp[0][0] = true;
34
        for ($i = 1; $i <= $m; $i++) {
35
            $dp[$i][0] = false;
36
        }
37
        for ($j = 1; $j <= $n; $j++) {
38
            $dp[0][$j] = true;
39
        }
40
41
        for ($i = 1; $i <= $m; $i++) {
42
            for ($j = 1; $j <= $n; $j++) {
43
                if ($s[$i - 1] === $t[$j - 1]) {
44
                    $dp[$i][$j] = $dp[$i - 1][$j - 1];
45
                } else {
46
                    $dp[$i][$j] = $dp[$i][$j - 1];
47
                }
48
            }
49
        }
50
51
        return $dp[$m][$n];
52
    }
53
}
54