[leetcode]ZigZag Conversion

ZigZag Conversion

Difficult:Medium

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

分析:

问题就是要Z字型输出字符串。

我的实现方法是按要求的行数创建临时的字符串(例如当行数等于3时有s1、s2、s3三个字符串),遍历输入的字符串的时候,按Z字型的顺序把每一位字符放接到临时字符串后边(比如第1个字符接s1后面,第2个接s2,第3个接s3,第4个就又接到s2,第5个接s1,第6个接s2.....),最后再把临时字符串接在一起就好了


 string convert(string s, int numRows) {
	 vector<string> v_result;
	 for (int i = 0; i < numRows; i++){
		 v_result.push_back("");//按行数生成临时字符串
	 }
	 int step = 1;//初始步进1,步进为1或-1
	 if (numRows < 2)//如果行数为1则步进为0
		 step = 0;
	 int current = 0;

	 for (int i = 0; i < s.size(); i++){

		 stringstream stream;
		 stream << s.at(i);
		 string tmp = stream.str();
		 v_result.at(current).append(tmp);//接到相应的临时字符串后面

		 current = current + step;//加上步进
		 if (current == 0 || current == numRows - 1)//当current为0或行数时,反转步进
			 step = step*-1;
	 }

	 string result = "";
	 for (int i = 0; i < numRows; i++){
		 result.append(v_result.at(i));
	 }
	 return result;
 }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值