Leetcode 0006: 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 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)
找规律:
1、对于第一行和最后一行,是公差为 2(n−1) 的等差数列,首项是 0 和 n−1;
2、对于其他行(0<i<n−1),是两个公差为 2(n−1) 的等差数列交替排列,首项分别是 i 和 2n−i−2;

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();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113798847