Leetcode 0006: ZigZag Conversion

本文介绍如何使用Python编写代码,将给定字符串PAYPALISHIRING按照指定行数以Zigzag模式进行布局,如PAHNAPLSIIGYIR。通过理解等差数列规律,演示了如何构造算法来适应不同行数的转换需求。
摘要由CSDN通过智能技术生成

题目描述:

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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值