标签:
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 RAnd 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"
.
1 class Solution { 2 public: 3 string convert(string s, int nRows) { 4 if(nRows==1) 5 { 6 return s; 7 } 8 string result; 9 int n=s.length(); 10 int step; 11 bool flag; 12 for(int i=0;i<nRows;i++) 13 { 14 int j=i; 15 flag=false; 16 while(j<n) 17 { 18 result.push_back(s[j]); 19 if(i==0||i==nRows-1) 20 { 21 step=2*(nRows-1); 22 } 23 else 24 { 25 if(flag==false) 26 { 27 step=2*(nRows-1-i); 28 flag=true; 29 } 30 else 31 { 32 step=2*i; 33 flag=false; 34 } 35 } 36 j+=step; 37 } 38 } 39 return result; 40 } 41 };
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4251631.html