ZigZag Conversion

原题链接-M

Example
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P I N
A L S I G
Y A H R
P I

时间复杂度: O(N)- 空间复杂度: O(N)

print_r(test("PAYPALISHIRING",3));

function test($str,$num) {
    if ($num==1||$num>=mb_strlen($str)) {
        return $str;
    } 
    
    $arr = [];
    $index = 0;
    $step = 1;
    
    for ($i = 0; $i < mb_strlen($str); $i++) {
         $arr[$index][] = $str[$i];
         if ($index == 0) {
             //代表往下走 
             $step = 1;
         } elseif ($index == $num - 1) {
             //代表往上走
             $step = -1;
         }
         $index += $step;
    }
    $endArr = [];
    foreach ($arr as $ar) {
        $endArr[] = implode('',$ar);
    }
    return implode('', $endArr);
}

你可能感兴趣的:(ZigZag Conversion)