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"
.
#include<iostream>
#include<string>
using namespace std;
class Solution{
public:
int convert(string s,int nRows);
};
int Solution::convert(string s,int nRows){
int length=s.length();
int interval=2*nRows-2;
for(int i=0;i<nRows;i++){//for
if(i==0 || i==nRows-1){
int m=i;
int j=0;
while(interval*j<length){
cout<<s[interval*j+m];
j++;
}
}else{//else2
int j=0;int k=j%2;
int poshead=(nRows-1-i)*2+i;
int m=0;
while(i+interval*j/2<length && m*interval+poshead < length ){
while(i+interval*j/2<length && k==0){
cout<<s[i+interval*j/2];
j++;k=j%2;
}
m=(j-1)/2;
while(m*interval+poshead < length && k==1){
cout<<s[m*interval+poshead];
j++;k=j%2;
}
}
}//else2
}//for
return 1;
}//convert
int main(){
string s="0123456789";
Solution sol;
sol.convert(s,4);
return 1;
}