6 ZigZag Conversion
P A H N
A P L S I I G
Y I Rstring convert(string text, int nRows);string convert(string s, int numRows) {
if (s.empty())
return s;
vector<vector<char>> zigs(numRows);
int row = 0, col = 0;
// 0 1 2 1 0 1 2 0 1 2 0 1 2…
/*
P A H N
A P L S I I G
Y I R
*/
int cur_index = 0;
int reset = 1;
while (cur_index < s.length()) {
for (row; row < numRows && cur_index < s.length(); row++) {
zigs.at(row).push_back(s.at(cur_index++));
}
for (row = row - 2; row >= 0 && cur_index < s.length(); row--) {
zigs.at(row).push_back(s.at(cur_index++));
}
row = reset;
}
//print2d(zigs);
string ret_str;
int iter = 0;
int where = 0;
for (int i = 0; i < zigs.size(); i++) {
for (int j = 0; j < zigs.at(i).size(); j++) {
ret_str.insert(where++, string(1, zigs.at(i).at(j)));
}
iter++;
}
return ret_str;
}
int main() {
string conv = "PAYPALISHIRING";
cout << convert(conv, 3) << endl;
pause();
}Last updated