Date: 2020-10-9
Author: 19th LZ
Tag: JAVA
Title description
Arrange a given character string in a zigzag pattern from top to bottom and from left to right according to a given number of lines.
For example, when the input string is "LEETCODEISHIRING" and the number of rows is 3, the arrangement is as follows:
L C I R
E T O E S I I G
E D H N
After that, your output needs to be read line by line from left to right to generate a new string, such as: "LCIRETOESIIGEDHN".
Please implement this function that transforms a string into a specified number of lines:
string convert(string s, int numRows);
Example:
示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:
L D R
E O E I I
E C I H N
T S G
Problem-solving ideas:
Use 2numRows-2 as a loop cyc, and
just output it directly according to the formula. The
first line and the last line have a difference of one cyc between each character;
each character in the middle part has a difference of cyc-2i (i means the first row) , And 2i;
Code
class Solution {
public String convert(String s, int numRows) {
if(numRows==1)
return s.toString();
StringBuilder result= new StringBuilder();
int all=s.length();
int cyc=2*numRows-2;
for(int j=0;j<all;j+=cyc){ //第一行
result.append(s.charAt(j));
}
for(int i=1;i<numRows-1;i++){ //中间部分
for(int j=i;j<all;){
result.append(s.charAt(j));
j+=cyc-2*i;
if(j<all){
result.append(s.charAt(j));
j+=2*i;
}
}
}
for(int j=numRows-1;j<all;j+=cyc){ //最后一行
result.append(s.charAt(j));
}
return result.toString();
}
}