Leetcode 0006: ZigZag Conversion

Title description:

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 s, int numRows);

Example 1:

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”

Example 2:

IInput: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P _ _ I _ _ N
A _ L S _ I G
Y A _ H R _ _
P _ _ I _ _ _

Example 3:

Input: s = “A”, numRows = 1
Output: “A”

Constraints:

1 <= s.length <= 1000
s consists of English letters (lower-case and upper-case), ‘,’ and ‘.’.
1 <= numRows <= 1000

Time complexity: O(n)
to find the law:
1. For the first row and the last row, it is an arithmetic sequence with a tolerance of 2(n−1), and the first term is 0 and n−1;
2. For other rows (0 <i<n−1), is the alternate arrangement of two arithmetic series with tolerance of 2(n−1), the first term is i and 2n−i−2 respectively;

class Solution {
    
    
    public String convert(String s, int numRows) {
    
    
        if(numRows == 1) return s;
        StringBuilder res = new StringBuilder();
        int len = s.length();
        int n = numRows;
        for(int i = 0; i < n; i++){
    
    
            if(i == 0 || i == n-1){
    
    
                for(int j = i; j < len; j+= 2*n-2){
    
    
                    res.append(s.charAt(j));
                }
            }else{
    
    
                for(int j = i, k = 2*n -2 - i; j < len || k < len; j+= 2*n-2, k+=2*n-2 ){
    
    
                    if(j < len) res.append(s.charAt(j));
                    if(k < len) res.append(s.charAt(k));
                }
            }
        }

        return res.toString();
    }
}

Guess you like

Origin blog.csdn.net/weixin_43946031/article/details/113798847