ZigzagConversion   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 14
eloc 25
c 2
b 0
f 0
dl 0
loc 42
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A convert2() 0 18 6
B convert() 0 20 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class ZigzagConversion
8
{
9
    public static function convert(string $str, int $numRows): string
10
    {
11
        [$m, $n] = [$numRows, strlen($str)];
12
        if ($m <= 1 || $m >= $n) {
13
            return $str;
14
        }
15
        [$s, $k] = ['', 2 * $m - 2];
16
        for ($i = 0; $i < $m; $i++) {
17
            for ($j = $i; $j < $n; $j += $k) {
18
                $s .= $str[$j];
19
                if ($i !== 0 && $i !== $numRows - 1) {
20
                    $t = $j + $k - 2 * $i;
21
                    if ($t < $n) {
22
                        $s .= $str[$t];
23
                    }
24
                }
25
            }
26
        }
27
28
        return $s;
29
    }
30
31
    public static function convert2(string $str, int $numRows): string
32
    {
33
        [$m, $n] = [$numRows, strlen($str)];
34
        if ($m <= 1 || $m >= $n) {
35
            return $str;
36
        }
37
        [$ans, $key, $step] = [array_fill(0, $m, ''), 0, 1];
38
        for ($i = 0; $i < $n; $i++) {
39
            $ans[$key] .= $str[$i];
40
            if ($key === 0) {
41
                $step = 1;
42
            } elseif ($key === $m - 1) {
43
                $step = -1;
44
            }
45
            $key += $step;
46
        }
47
48
        return implode('', $ans);
49
    }
50
}
51