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 R
And 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".
stringconvert(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;}intmain() { string conv ="PAYPALISHIRING"; cout <<convert(conv,3) << endl;pause();}