Test Failed
Push — master ( f110ed...37805d )
by Jinyun
03:03
created

ReverseStringII::reverseStr()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 15
rs 9.6111
cc 5
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class ReverseStringII
8
{
9
    public static function reverseStr(string $s, int $k): string
10
    {
11
        if (empty($s) || $k <= 0) {
12
            return '';
13
        }
14
        $n = strlen($s);
15
        for ($m = 0; $m < $n; $m += 2 * $k) {
16
            for ($i = $m, $j = min($m + $k - 1, $n - 1); $i < $j; $i++, $j--) {
17
                $t = $s[$i];
18
                $s[$i] = $s[$j];
19
                $s[$j] = $t;
20
            }
21
        }
22
23
        return $s;
24
    }
25
26
    public static function reverseStr2(string $s, int $k): string
27
    {
28
        if (empty($s) || $k <= 0) {
29
            return '';
30
        }
31
        [$i, $n] = [0, strlen($s)];
32
        while ($i < $n) {
33
            $j = min($i + $k - 1, $n - 1);
34
            $m = $j + $k + 1;
35
            while ($i < $j) {
36
                $t = $s[$i];
37
                $s[$i] = $s[$j];
38
                $s[$j] = $t;
39
                $i++;
40
                $j--;
41
            }
42
            $i = $m;
43
        }
44
45
        return $s;
46
    }
47
}
48