ZigZag Conversion (Easy)

Description

1
2
3
4
5
6
7
8
9
10
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".

Analysis

Easy部分的最后一题了。还有几题是要购买才能做的= =。做了一天。
easy部分除了购买部分一共39题。明天开始做medium部分了。
这题。。我是找规律的= =。sad。

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//C++
class Solution {
public:
string convert(string s, int nRows) {
string ans;
int len = s.length();
if(nRows>=len||nRows<=1)
return s;
int n = 2*nRows-2;
for(int i = 1,j = 1;i<=nRows;j=++i){
if(i==1||i==nRows){
while(j<=len){
ans+=s[j-1];
j+=n;
}
}
else{
int x = n-2*(i-1);
int y = 2*(i-1);
while(j<=len){
ans+=s[j-1];
j+=x;
if(j<=len)
ans+=s[j-1];
j+=y;
}
}
}
return ans;
}
};