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

一、题目描述

将给定的字符串,变成z字形排列,结果输出按行拼接的字符。例如字符串"PAYPALISHIRING"且nRows为3时,结果输出为:"PAHNAPLSIIGYIR"

二、解题思路

1.第0行和最后一行中,前一个下标的值和后一个下标的值相差 2 * nRows - 2 ;
2.中间行中,前一个下标的值和后一个下标的值需要根据这个下标是该行中的奇数列还是偶数列来计算; 奇数列,从这个下标到下一个下标相差的值是它们所处 的行i下面的所有行的点的个数,即2 * (nRows - 1 - i); 偶数列,从这个下标到下一个下标相差的值其实是它们所处的行i上面的所有行的点的个数,即2 * i。

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;

class Solution {
public:
	string convert(string s, int nRows) {
		// IMPORTANT: Please reset any member data you declared, as
		// the same Solution instance will be reused for each test case.  

		if (nRows <= 1 || s.length() == 0)
			return s;

		string zigzagString = "";
		int len = s.length();
		for (int i = 0; i < len && i < nRows; ++i)
		{
			int indx = i;
			zigzagString += s[indx];

			for (int k = 1; indx < len; ++k)
			{
				//第一行或最后一行
				if (i == 0 || i == nRows - 1)
				{
					indx += 2 * nRows - 2;
				}
				//中间行,判断奇偶
				else
				{
					if (k & 0x1)  //奇数
						indx += 2 * (nRows - 1 - i);
					else indx += 2 * i;
				}

				//判断indx合法性
				if (indx < len)
				{
					zigzagString += s[indx];
				}
			}
		}
		return zigzagString;
	}
};

int main()
{
	string s1 = "PAYPALISHIRING";
	int n = 4;
	Solution solution1;
	string s2 = solution1.convert(s1, n);
	cout<<s2<< endl;
	system("pause");
	return 0;
}

LeetCode6:ZigZag Conversion_第1张图片




你可能感兴趣的:(LeetCode6:ZigZag Conversion)