ZigZag Conversion [LeetCode]

时间:2023-03-09 03:29:22
ZigZag Conversion [LeetCode]

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".

Summary: just finds the index in string s of every rows.

     string convert(string s, int nRows) {
string output;
if(nRows <= )
return output;
if(nRows == || nRows == s.size())
return s; for(int i = ; i < nRows; i ++) {
if(i == || i + == nRows){
int j = i;
while(j < s.size()){
output += s[j];
j += nRows + nRows - ;
}
}else{
int j = + i;
while(j < s.size()){
output += s[j];
int next_idx = j + nRows - (i + ) + nRows - (i + );
if(next_idx < s.size())
output += s[next_idx];
j += nRows + nRows - ;
}
}
}
return output;
}