<?php
/**
* N 字形变换
*
* User: hihone
* Date: 2019/2/1
* Time: 14:26
* Description:
* 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 N 字形排列。
* 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
* L C I R
* E T O E S I I G
* E D H N
*/
/**
* @param $s
* @param $numRows
*
* @return string
*/
function convert($s, $numRows)
{
if ($numRows == 1) return $s;
$len = min(strlen($s), $numRows);
$data = [];
#构造行数
for ($i = 0; $i < $len; $i++) array_push($data, []);
$curRow = 0;
$down = false;
foreach (str_split($s) as $key => $val) {
array_push($data[$curRow], $val);
if ($curRow == 0 || $curRow == $numRows - 1) $down = !$down;
$down ? ++$curRow : --$curRow;
}
$result = [];
array_map(function ($value) use (&$result) {
$result = array_merge($result, array_values($value));
}, $data);
return implode('', $result);
}
$s = 'PAYPALISHIRING';
$r = convert($s, 3);
echo $r;#PAHNAPLSIIGYIR
网友评论