ZigZag Conversion - LeetCode 6

题目描述:
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 LS 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".
Hide Tags String

分析:所谓ZigZag Conversion,就是将一个字符串根据指定行数,按照“蛇形”的排列起来,此处的“蛇形”是先竖直方向,然后副对角线方向,从左往右进行。举个栗子:
将序列"0123456789876543210"按5行进行转换后为:
0    8    2  
1  79  31
2 6 8 4 0
35  75
4    6 
那么得到的输出序列则为:"0821793126840357546"

于是可以将转换后的元素按行存起来,然后再拼接起来即可。

以下是C++实现代码:

/*///24ms/*/
class Solution {
public:
    string convert(string s, int n) {
        if(n == 1)
			return s;
        vector<string> vec(n,""); //存储转换后的每行
		int len = s.size();
		int i = 0,j = 0;
		while(i < len)
		{
			for(j = 0;j < n && i < len; j++)
				vec[j].push_back(s[i++]); // 竖直方向,上到下,需要n个字符,依次字符追加到对应行的字符串中

			for(j = j-2;j > 0 && i < len; j--)
				vec[j].push_back( s[i++]); //副对角线方向,下到上,一共需要n-2个字符,依次字符追加到对应行的字符串中
		}
		string res = "";
		for(int j = 0; j < n; j++) // 拼接得到结果字符串
			res.append(vec[j]);
		return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值