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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P     I    N
A   L S  I G
Y A   H R
P     I

Example 3:

Input: s = "A", numRows = 1
Output: "A"

Constraints:

1 <= s.length <= 1000
s consists of English letters (lower-case and upper-case), ',' and '.'.
1 <= numRows <= 1000

实现思路:

题目的要求就是将一个字符串从由上至下,从左往右斜着构建一个逻辑上的Z字形,然后在按照层序方式输出所有的字符。
本题的做法首先就是寻找一个规律,

以下就是规律截取部分  N=3时
P   A
A P    
Y 					

N=4时
	
P      I
A    L
Y A
P

N=5时
	
P       H
A     S
Y   I
P L
A

每一次输出一行的第二个元素的空格数据位置是2*rowNums-2,这就是规律。
然后需要注意除了第一行和最后一行之外的中间行数中间的斜着的数据需要单独处理,寻找规律即可。

AC代码

class Solution {
	public:
		string convert(string s, int numRows) {
			if(s.length()==0||numRows<=0) return "";
			if(numRows==1) return s;
			string str="";
			int size=2*numRows-2;
			for(int i=0; i<numRows; i++) {
				for(int j=i; j<s.length(); j+=size) {
					str+=s[j];
//			单独处理除了第一行和最后一行以外的情况
					if(i!=0&&i!=numRows-1&&(j+size-(2*i)<s.length())) {
						str+=s[j+size-(2*i)];
					}
				}
			}
			return str;
		}
};
上一篇:Codeforces Round #539 (Div. 2)


下一篇:ZigZag Conversion(C++字形变换)