Monday, May 11, 2015

ZigZag Conversion

来源:Leetcode

原帖:http://oj.leetcode.com/problems/zigzag-conversion/

题目:
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".

代码:
 class Solution {  
 public:  
   string convert(string s, int nRows) {  
     if (nRows == 1) return s;  
     string res;  
     int inc = (nRows - 1) * 2;  
     int N = s.size();  
     for (int r = 0; r < nRows; ++r) {  
       int i = r;  
       while (i < N) {  
         if ((r == 0 || r == nRows - 1) && i < N) {  
           res.push_back(s[i]);  
           i += inc;   
         } else {  
           if (i < N) res.push_back(s[i]);  
           if (inc + i - 2 * r < N) res.push_back(s[inc + i - 2*r]);  
           i += inc;  
         }  
       }  
     }  
     return res;  
   }  
 };  

No comments:

Post a Comment