题目描述:
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"
.
分析:
题意:ZigZag的中文含义是“锯齿形的,之字形的, Z字形的”,顾名思义,这道题是给定一个字符串,按照Z字形排列,返回它的按行读取字符组成的字符串。
思路:这是一道找规律的数学题,我们发现,当设为nRows行时,第一行和最后一行,水平相邻字符之间的距离step = 2 * nRows - 2,中间第i行(0, 1, 2, ..., nRows - 1)水平间距为step' = step - 2 * i。
注意一点:当nRows=1时,刚好排成一条水平线;当nRows大于等于字符串长度时,刚好排成一条竖直线,这两种情况可以特殊考虑。假设字符串的长度为n,则时间复杂度为O(n * nRows))。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
int n = s.length();
// Exceptional Case:
if(n == 0 || numRows == 1 || n <= numRows){
return s;
}
string ans, tmp = "#";
int step = 2 * numRows - 2;
for(int i = 0; i <= numRows - 1; i++){
int j = i;
if(i == 0 || i == (numRows - 1)){
while(j <= n - 1){
tmp[0] = s[j];
ans += tmp;
j += step;
}
}
else{
int ss = step - i * 2;
while(j <= n - 1){
tmp[0] = s[j];
ans += tmp;
j += ss;
ss = step - ss;
}
}
}
return ans;
}
};