[LeetCode] ZigZag Conversion 解题报告

—— write for my baby, mua


[题目]

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


[中文翻译]

字符串"PAYPALISHIRING"写成给定行数的ZigZag模式如下:(为了更好的可读性,你可能需要以固定字体显示这个模式)

P   A   H   N
A P L S I I G
Y   I   R
然后将该模式按行读: "PAHNAPLSIIGYIR"

给定字符串和行数,编写代码完成这个转换:

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) 返回 "PAHNAPLSIIGYIR"


[解题思路]

zigZag模式,即将原来的字符串,按下图方式依次排列。

图1. ZigZag模式


O(M+N) M=len(text), N=nRows

如果nRows<=1,则直接返回text

否则,创建N个字符串,分别表示ZigZag模式的N行。遍历text的字符,将字符循环往复地插入N个字符串中,可以用一个指针(整数)表示当前字符要插入第几个字符串。

最后,将N个字符串连接,返回结果。


[C++代码]

class Solution {
public:
	string convert(string s, int numRows) {
		if (numRows <= 1)
			return s;

		string* line = new string[numRows];
		int index = 0, dircetion = 1, lineIndex = 0;

		while (index < s.size()) {
			if (lineIndex < 0) {
				lineIndex = 1;
				dircetion = -dircetion;
			}
			else if (lineIndex >= numRows) {
				lineIndex = numRows - 2;
				dircetion = -dircetion;
			}
			
			line[lineIndex] = line[lineIndex] + s.at(index);
			index++;
			lineIndex += dircetion;
		}

		string res = "";
		for (int i = 0; i < numRows; i++)
			res = res + line[i];

		return res;
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值