zigzag相关题目2--LeetCode(6) ZigZag Conversion

题目要求:
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".
思路:

用一个vector<string>存储每一行的string,j=i%(2 * numRows - 2);当j<nRows,row=j,当j>=nRows,row=2*nRows-j-2;*/

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iostream>
#include<vector>

using namespace std;

class Solution1 {
public:
	string convert(string s, int numRows) {
		if (numRows == 1)
			return s;
		const int Rows = numRows;
		vector<string> line(Rows);
		int i;
		int j;
		int row;
		for (i = 0; i < s.size(); ++i)
		{
			j = i % (2 * numRows - 2);
			if (j >= numRows)
				row = 2 * numRows - j - 2;
			else
				row = j;
			line[row] += s[i];
		}
			string result;
			for (i = 0; i < numRows; ++i)
				result += line[i];
			return result;				
	}
};
/*
另一种解法:
第0行和最后一行中,前一个下标的值和后一个下标的值相差 2 * nRows - 2 ,以第0行为例,前一个下标为0,
后一个下标为 0+2*4-2=6。
中间行中,前一个下标的值和后一个下标的值需要根据这个下标是该行中的奇数列还是偶数列来计算。以平时的习惯
来计算,因此,行和列的开始值都是0。
以第2行为例,第一个下标是2,后一个下标所处列为1,是奇数列,因此从这个下标到下一个下标相差的值是它们所处
的行i下面的所有行的点的个数,即2 * (nRows - 1 - i)。在这里,nRows-1是为了遵循0下标开始的原则。这样,我们可以
求得这个奇数列的下标为 2+2*(4-1-2)=4。同理,当我们要计算4之后的下标时,我们发现下一个所处的是偶数列2,从这个
下标到下一个下标相差的值其实是它们所处的行i上面的所有行的点的个数,即2 * i。因此,该列的下标计算为4+2*2=8。


有了以上的公式,我们就可以写出代码了。但需要注意几点:
1.判断所求出的下标是不是越界了,即不能超出原字串的长度;
2.注意处理nRows=1的情况,因为它会使差值2 * nRows - 2的值为0,这样下标值会一直不变,进入死循环,产生
Memory Limit Exceeded 或者 Output Limit Exceeded之类的错误。
3.还有一些其他的边界情况,如:nRows > s.length,s.length = 0等需要处理。


*/


class Solution {
public:
	string convert(string s, int numRows) {
		if (numRows <= 1 || s.length() == 0)
			return s;
		string res = "";
		int len = s.length();
		for (int i = 0; i < len&&i < numRows; ++i)
		{
			int index = i;
			res += s[index];
			for (int k = 1; index < len; ++k)
			{
				if (i == 0 || i == (numRows - 1))
				{
					index += 2 * numRows - 2;
				}
				else
				{
					if (k & 0x1)
						index += 2 * (numRows - 1 - i);
					else
						index += 2 * i;
				}
				if (index < len)
				{
					res += s[index];
				}
			}

		}

		return res;
	}
};


参考:

http://blog.csdn.net/zhouworld16/article/details/14121477

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值