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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
string ans="";
if(s=="" || numRows==1) return s;
int len = numRows+numRows-2;
int num = s.length()/len, remain=s.length()-num*len;
for(int i=0; i < num; i++) {
ans+=s[i*len];
}
if(remain>0) ans+=s[num*len];
for (int j = 1; j < numRows-1; ++j)
{
for (int i = 0; i < num; ++i)
{
ans += s[i*len+j];
ans += s[i*len+j+2*(numRows-1-j)];
}
if(remain > 0) {
if(num*len+j < s.length())
ans += s[num*len+j];
if(num*len+j+2*(numRows-1-j) < s.length())
ans+= s[num*len+j+2*(numRows-1-j)];
}
}
for (int i = 0; i < num; ++i)
{
ans+=s[i*len+numRows-1];
}
if(remain > 0) {
if(num*len+numRows-1 < s.length())
ans+= s[num*len+numRows-1];
}
return ans;
}
};