zigzag transformation
Arrange a given string s in zigzag from top to bottom and from left to right according to the given number of rows numRows.
For example, when the input string is "PAYPALISHIRING" and the number of lines is 3, the arrangement is as follows:
After PAHN
APLSIIG
YIR
, your output needs to be read line by line from left to right to produce a new string, for example: "PAHNAPLSIIGYIR".
Please implement this function to convert a string to a specified number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
PIN
ALSIG
YAHR
PI
Example 3:
Input: s = "A", numRows = 1
Output: "A"
hint:
1 <= s.length <= 1000
s consists of English letters (lowercase and uppercase), ',' and '.'
1 <= numRows <= 1000
Anger is a sign of incompetence, and this question made me very angry. . . After reading the selected solutions, this flag is too beautiful.
answer:
class Solution {
public String convert(String s, int numRows) {
if(numRows < 2) return s;
List<StringBuilder> rows = new ArrayList<StringBuilder>();
for(int i = 0; i < numRows; i++) rows.add(new StringBuilder());
int i = 0, flag = -1;
for(char c : s.toCharArray()) {
rows.get(i).append(c);
if(i == 0 || i == numRows -1) flag = - flag;
i += flag;
}
StringBuilder res = new StringBuilder();
for(StringBuilder row : rows) res.append(row);
return res.toString();
}
}