Test Failed
Push — master ( c6e15f...aeb9a7 )
by Jinyun
02:28
created

ValidPalindrome::isPalindrome2()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 20
rs 9.2222
cc 6
nc 6
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class ValidPalindrome
8
{
9
    public static function isPalindrome(string $s): bool
10
    {
11
        if (0 === ($n = strlen($s))) {
12
            return true;
13
        }
14
        $ans = [];
15
        for ($i = 0; $i < $n; $i++) {
16
            // Can also use ctype_alnum instead.
17
            if (preg_match('/^[a-zA-Z0-9]$/', $s[$i])) {
18
                array_push($ans, strtolower($s[$i]));
19
            }
20
        }
21
22
        return $ans === array_reverse($ans);
23
    }
24
25
    public static function isPalindrome2(string $s): bool
26
    {
27
        if (empty($s)) {
28
            return true;
29
        }
30
        [$i, $j] = [0, strlen($s) - 1];
31
        while ($i < $j) {
32
            if (!ctype_alnum($s[$i])) {
33
                $i++;
34
            } elseif (!ctype_alnum($s[$j])) {
35
                $j--;
36
            } elseif (strtolower($s[$i]) !== strtolower($s[$j])) {
37
                return false;
38
            } else {
39
                $i++;
40
                $j--;
41
            }
42
        }
43
44
        return true;
45
    }
46
47
    public static function isPalindrome3(string $s): bool
48
    {
49
        if (empty($s)) {
50
            return true;
51
        }
52
        $s = strtolower($s);
53
        [$i, $j] = [0, strlen($s) - 1];
54
        while ($i < $j) {
55
            if (!ctype_alnum($s[$i])) {
56
                $i++;
57
            }
58
            if (!ctype_alnum($s[$j])) {
59
                $j--;
60
            }
61
            if (ctype_alnum($s[$i]) && ctype_alnum($s[$j])) {
62
                if ($s[$i] !== $s[$j]) {
63
                    return false;
64
                }
65
                $i++;
66
                $j--;
67
            }
68
        }
69
70
        return true;
71
    }
72
}
73