[Leetcode 42] 6 ZigZag Conversion
Problem:
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:
First of all, you should know what's the meaning of zigzag. To understand more, try some more examples.
If n = 2, then "PAYPALISHIRING" is arranged into:
P Y A I H R N
A P L S I I G
and converted into "PYAIHRNAPLSIIG"
If n = 4, then "PAYPALISHIRING" is arranged into:
P I N
A L S I G
Y A H R
P I
If n = 5, then "PAYPALISHIRING" is arranged into:
P H
A S I G
Y I R N
P L I
A
Now try to find the relationship of characters in the same row. We may find that, for elements in
n = 2, two characters in the same row's index differs 2
n = 3, first line's characters' index differs 4; second line's characters' index differs 2 2; third line's characters' index differs 4;
n = 4, first line's characters' index differs 6; second line's characters' index differs 4 2; third line's characters' index differs 2 4; fourth line difffers 6;
n=5, first line differ 8; second line differ 6 2; third line differ 4 4; fourth line differ 2 6; fifth line differ 0 8;
It's clear that there is a relationship. If think carefully, you may find the relationship is as follows:
fp = 2*(n-1), sp=2*i; Then the next element is draw from current index plus fp/sp staggered.
So the solution is as follows.
Code:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 string convert(string s, int nRows) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (nRows == 1) return s; 7 8 char res[s.length()]; 9 int idx = 0; 10 11 for (int i=0; i<nRows; i++) { 12 int fp = 2*(nRows - i - 1); 13 int sp = 2*i; 14 15 bool flag = true; 16 for (int j=i; j<s.length(); ) { 17 if (flag) { 18 if (fp != 0) 19 res[idx++] = s[j]; 20 j += fp; 21 } 22 else { 23 if (sp != 0) 24 res[idx++] = s[j]; 25 26 j += sp; 27 } 28 29 flag = !flag; 30 } 31 } 32 res[idx] = '\0'; 33 34 string r(res); 35 return r; 36 } 37 };