The number of a given string according to the given row, to down, left to right from the Z-shaped arrangement.
Example, the input string is the number of rows "LEETCODEISHIRING" is 3, arranged as follows:
LCIR
ETOESIIG
EDHN
After that, you need the output from left to right read line by line, produce a new string, such as: "LCIRETOESIIGEDHN".
You will realize this string conversion function specified number of lines:
string convert (string s, int numRows );
Example 1:
Input: s = "LEETCODEISHIRING", numRows = 3
Output: "LCIRETOESIIGEDHN"
Example 2:
Input: s = "LEETCODEISHIRING", numRows = 4
Output: "LDREOEIIECIHNTSG"
explanation:
L D R
E O E I I
E C I H N
T S G
Source: stay button (LeetCode)
The answer presented
class Solution {
/**
* @param String $s
* @param Integer $numRows
* @return String
*/
function convert($s, $numRows) {
$ Len = strlen ($ s);
if($len <= $numRows || $numRows <= 1){
return $s;
}
$str = [];
$line = 1;
$add = true;
for($i = 0;$i < $len;$i ++ ){
$str[$line][]= $s[$i];
if($line == 1){
$add = true;
}elseif($line == $numRows){
$add = false;
}
if($add){
++$line;
}else{
--$line;
}
}
$res = '';
for($m = 0;$m < $numRows;$m++){
$res.=implode('',$str[$m+1]);
}
return $res;
}
}