Leetcode6-Z font transformation

Arrange a given character string in a zigzag pattern from top to bottom and from left to right according to the given number of lines.
For example, when the input string is "LEETCODEISHIRING" and the number of rows is 3, the arrangement is as follows:

After LCIR
ETOESIIG
EDHN
, your output needs to be read line by line from left to right to produce a new string, such as: "LCIRETOESIIGEDHN".

Please implement this function that transforms the string to the specified number of lines:

string convert(string s, int numRows);
示例 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

String segmentation
len = 2 * numRows-2;

 public String convert(String s, int numRows) {
        String x="";
        int len=2*numRows-2;
        if(len==0){  //避免分母为0;
          return s;
        }
    for(int i=0;i<numRows;i++){  //逐行读取
        for(int j=0;j<s.length();j++){
            if(j%len==i||len-j%len==i){ //符合条件的字符重新编排
                x+=s.charAt(j);
            }
        }
    }
    return x;
    }
Published 6 original articles · liked 0 · visits 19

Guess you like

Origin blog.csdn.net/qq_44158395/article/details/105385685