1 /* 2 * Just find the rule; Do not forget to check 3 * special cases (e.g. nRows = 1 ...) 4 * 5 * @author: HZT 6 * @date: 2013-3-9 7 */ 8 9 #include <iostream> 10 #include <string> 11 using namespace std; 12 13 class Solution { 14 public: 15 string convert(string s, int nRows) { 16 // Start typing your C/C++ solution below 17 // DO NOT write int main() function 18 19 // DO NOT forget this!! 20 if(nRows == 1) return s; 21 if(s.empty()) return s; 22 int len = s.length(); 23 24 char* ans = new char[len+1]; 25 26 int idx, ansIdx=0; 27 int delta = 2 * nRows - 2; 28 // each row 29 for(int r=1; r<=nRows; r++){ 30 idx = r; 31 while(idx <= len){ 32 ans[ansIdx++] = s[idx-1]; 33 if(r!=1 && r!=nRows && 2*nRows-2*r+idx <= len){ 34 ans[ansIdx++] = s[2*nRows-2*r+idx-1]; 35 } 36 37 idx += delta; 38 } 39 } 40 41 ans[len] = '\0'; 42 return ans; 43 } 44 }; 45 46 int main(){ 47 string s = "PAYPALISHIRING"; 48 int nRows = 3; 49 50 //string s = "A"; 51 //int nRows = 1; 52 53 cout << (new Solution)->convert(s, 3) << endl; 54 55 return 0; 56 57 }