ZigZag Conversion (Java)

本文详细介绍了如何使用特定的算法将给定的字符串转换为zigzag模式,并且提供了相应的代码实现。其中包括如何处理不同行的数据,以及如何确定字符串中每个字符在zigzag模式下的正确位置。

摘要生成于 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".


把第一行和最后一行拿出来单独处理  i指向行  

其他行可以发现规律如下


从0---7是一个拐角  每个拐弯有2n-2个数

j指向每个拐角的第i行第一个数  如 i=1时 j = i step j = j + 2n-2 如图 j = 1,9……

剩下就是如何插入7了,通过观察可以看出7的位置是2*(n-2-i) 即在j和7中间有多少个数,除却最后一行的4以及7本身,中间剩下的为n-2-i行,每行2个数,故此位置可用j+2*(n-2-i)得出

Source

public class Solution {
	public static String convert(String s, int nRows) {
		int i = 0, j, cnt = 0,k;
		StringBuffer a = new StringBuffer();		//string没有append类
		
		if(s == null || s.length() <= nRows || nRows <= 1) return s;		//注意这几种特殊情况
		for(i = 0; i < s.length(); i = i + 2 * nRows - 2)		//每个拐弯是2n-2个字符 处理第一行
			a.append(s.charAt(i));		//append用于在字符串末尾添加新字符
		for(i = 1; i < nRows - 1; i++)		//中间行按行分别处理
		{
			for(j = i; j < s.length(); j = j + 2 * nRows -2)  //每个拐弯的这个位置
			{
				a.append(s.charAt(j));
				if(j + 2 * nRows - 2 - 2 * i < s.length())		
				{
					a.append(s.charAt(j + 2*nRows - 2 - 2 * i));
				}
			}
		}		
		for(i = nRows -1; i < s.length(); i = i + 2 * nRows - 2)		//处理最后一行
			a.append(s.charAt(i));
		return a.toString();		//将stringbuffer转换为string

	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值