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.

 1     string convert(string s, int nRows) {

 2         string output;

 3         if(nRows <= 0)

 4             return output;

 5         if(nRows == 1 || nRows == s.size())

 6             return s;

 7             

 8         for(int i = 0; i < nRows; i ++) {

 9             if(i == 0 || i + 1 == nRows){

10                 int j = i;

11                 while(j < s.size()){

12                     output += s[j];

13                     j += nRows + nRows - 2;

14                 }

15             }else{

16                 int j = 0 + i;

17                 while(j < s.size()){

18                     output += s[j];

19                     int next_idx = j + nRows - (i + 1) + nRows - (i + 1);

20                     if(next_idx < s.size())

21                         output += s[next_idx];

22                     j += nRows + nRows - 2;

23                 }

24             }                                                                                                                                                                                                                               

25         }

26         return output;

27     }

 

你可能感兴趣的:(conversion)