天天看點

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