6. ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

一刷
题解:

根据例子列出n = 3和n = 4的情况,计算出列间距zigSize = 2 * numRows - 2,所以每行元素为 i + n * zigSize以及斜线的计算公式,当i为行数时,斜线上元素为n * zigSize - i。

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {
    public String convert(String s, int numRows) {
        int zigSize = 2*numRows - 2;
        if(s == null || s.length() == 0 || zigSize <=0) return s;
        StringBuilder res = new StringBuilder();
        
        for(int i=0; i

你可能感兴趣的:(6. ZigZag Conversion)