【LeetCode】ZigZag Conversion

本文介绍了如何将给定的字符串转换为特定行数的zigzag格式,并提供了两种不同的算法实现方式,包括遍历字符串并使用vector存储字符的方法,以及直接找出规律进行计算的方法。

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

两种解法:

第一种是遍历s,将一个个字符写入vector<string>,最后将数组连起来输出。需要用一个变量来控制写入顺序。

第二种是直接找出规律,稍微写下就找的出来:步长STEP= 2 * nRows - 2,res+=s[(i / 2)*STEP + r]+s[(i / 2)*STEP + STEP - r],当然记得要判定边界条件。

代码如下,第一种方法96ms通过,第二种方法MLE,但代码没发现问题,在自己机子上跑也没问题,变量数明显应该比第一种方法少,不知为何MLE……仅供参考吧:

class Solution {
public:
	string convert(string s, int nRows) {
		vector<string> zz(nRows);
		int j(0);
		bool even(true);
		for (int i = 0; i < s.length(); i++){
			zz[j] += s[i];
			if (even)
				j++;
			else
				j--;
			while ((even && (j >= nRows || j < 0)) || (!even && (j >= nRows - 1 || j <= 0))){
				even = !even;
				if (even)
					j = 0;
				else
					j = nRows - 2;
			}
		}
		string res;
		for (int i = 0; i < nRows; i++)
			res += zz[i];
		return res;
	}
};
class Solution {
public:
	string convert(string s, int nRows) {
		if (nRows >= s.length() || nRows <= 0)
			return s;
		int STEP = 2 * nRows - 2;
		int N = s.length();
		string res;
		for (int r = 0; r < nRows; r++){
			int i = 0;
			while (1){
				if ((i / 2)*STEP + r >= N)
					break;
				res += s[(i / 2)*STEP + r];
				if ((i / 2)*STEP + STEP - r >= N)
					break;
				if (r != 0 && r != nRows - 1)
					res += s[(i / 2)*STEP + STEP - r];
				i += 2;
			}
		}
		return res;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值