【Leetcode Algorithm】ZigZag Conversion

本文介绍了一种特殊的字符串转换方法——ZigZag模式,该模式将输入字符串按Z形路径分布在多行中,再逐行读取形成新的字符串。文章提供了实现这一转换的Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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".

这道题题目给的不太明白,容易让不清楚ZigZag的人一头雾水,下面这个大家已看应该就清楚了

Zigzag:即循环对角线结构(

0



8



16
1


7 9


15 17
2

6

10

14

18
3 5


11 13


19
4



12



20

 

向下循环:nRows

斜角线循环:nRows-2(减去首尾两个端点)

重复


代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
    public String convert(String s, int numRows) {
        StringBuffer sb = new StringBuffer();
        if(numRows<2){
            return s;
        }
        else{
            //两列直接的对角线元素为numRows-2;因此定义两列之间的步长
            int step = 2*(numRows-1);
            for(int row=0;row<numRows;row++){
                //按照步长将第row行的非对角线元素添加进StringBuffer
                for(int j=row;j<s.length();j+=step){
                    sb.append(s.charAt(j));
                    //当第row行不是首行和尾行,且增加步长之后的索引在长度范围内时,将对角线上的元素添加到StringBuffer
                    if((row!=0&&row!=numRows-1)&&(j+step-row*2)<s.length()){
                        sb.append(s.charAt(j+step-row*2));
                    }
                }
            }
            return sb.toString();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值