6. ZigZag Conversion

本文介绍了一种算法,用于将字符串以Z形模式分布在指定数量的行上,然后按行读取形成新的字符串。例如,输入helloworld和4行,输出hoewrlolld。文章详细解释了实现这一功能的步骤和限制条件,并提供了完整的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"

如果找出规律来说不算难题。

这道是要一个String类型的字符串中的字母按照Z排序(其实是按照中心对称的N来排序),比如

String s = "helloworld";  int numRows = 4;
输出结果为 hoewrlolld

//排序的结构图如下

                        对应的index                对应的行数变化 int y = 0
第1行 h             o         0             6            +1              -1

第2行 e        w    r         1        5    7            +1        -1    +1

第3行 l    o        l         2    4        8            +1    -1        +1

第4行 l             d         3             9            +1              +1  

在 y == nowRows-1 前一直+1,随后在y=0 前一直-1.




思路在代码的注释中大致分为3步和几个限制条件

class Solution {
    public String convert(String s, int numRows) {
        //首先判断什么时候直接输出
    	if(s.length() == 1 || s.length() < numRows || numRows == 1){
    		return s;
    	}

    	//创建对应的sb存储对应的numRows行的字符
    	StringBuilder [] sb = new StringBuilder[numRows];
    	for(int i = 0; i < numRows ; i++){
    		sb[i] = new StringBuilder();
    	}

    	//将对应的字符按规律放入sb中
    	int y = 0;
    	int desc = 0;
    	for(int i = 0; i < s.length(); i++){
    		if(y == 0){
    			desc = 1;
    		}
    		if(y == numRows-1){
    			desc = -1;
    		}
    		sb[y].append(s.charAt(i));
    		y += desc; 
    	}
        
        //将行的sb拼装, 注意:i的初始值为1
    	for(int i = 1; i < numRows; i++){
    		sb[0].append(sb[i]);
    	}

    	return sb[0].toString();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值