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"
.
Subscribe to see which companies asked this question
class Solution {
public:
string convert(string s, int n) {
if(n==1) return s;
bool index1=true;
int j=0;
vector<vector<char>> v(n,vector<char>());
for(int i=0;i<s.size();)
{
if(index1)
{
if(j<n)
{
v[j++].push_back(s[i]);++i;
}
else
{
j-=2;
index1=!index1;
}
}
else
{
if(j>0)
{
v[j--].push_back(s[i]);
++i;
}
else
{
index1=!index1;
}
}
}
string s1="";
for(int i=0;i<n;++i)
for(int j=0;j<v[i].size();++j)
s1+=v[i][j];
return s1;
}
};