LeetCode——ZigZag Conversion

本文介绍了一种将字符串以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 s, int numRows);

  • Example 1:
    Input: s = “PAYPALISHIRING”, numRows = 3
    Output: “PAHNAPLSIIGYIR”
  • Example 2:
    Input: s = “PAYPALISHIRING”, numRows = 4
    Output: “PINALSIGYAHRPI”
    Explanation:
P     I    N
A   L S  I G
Y A   H R
P     I

题目意思是将字符按Z字型排列 即将0123456789排成

n=3
0		4		8
1	3	5	7	9
2		6
输出0481357926
n=4
0			6
1		5	7
2	4		8
3			9
输出0615724839

相邻两列中多了n-2个数字,因此每一行中的每个数字相邻2n-2,即当n=4时,0和6之间相差24-2.除第一行和最后一行外中间都有数字,中间数字的位置与它前一个数字相差2n-2-2i,i为行数(行数从零开始算)即n=4时,1和5之间相差24-2-21=4。知道它们的位置关系后便可以按顺序添加字符到新字符串中

public String convert(String s, int numRows) {
        if(numRows<=1)
        	return s;
        StringBuffer res=new StringBuffer();
        int size=2*numRows-2;
        for(int i=0;i<numRows;i++)
        {
        	for(int j=i;j<s.length();j+=size)
        	{
        		res.append(s.charAt(j));
        		int tmp=j+size-2*i;
        		if(i!=0&&i!=numRows-1&&tmp<s.length())
        			res.append(s.charAt(tmp));
        	}
        }
        return res.toString();
    }

Runtime: 19 ms, faster than 98.79% of Java online submissions for ZigZag Conversion.
Memory Usage: 39.5 MB, less than 82.45% of Java online submissions for ZigZag Conversion.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值