15.12—细节实现题—ZigZag Conversion

来源:互联网 发布:linux mount sd卡 编辑:程序博客网 时间:2024/06/02 07:05
描述
e string ”PAYPALISHIRING” is wrien in a zigzag paern on a given number of rows like this: (you
may want to display this paern in a fixed font for beer 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”.

#include<iostream>#include<string>using namespace std;string ZigZagCon(string str, int rows){if (rows == 1){string res = str;return res;}int len = str.size();string res;for (int i = 0; i<rows; i++){if (i == 0 || i == rows - 1){int j = i;while (j<len){res.push_back(str[j]);j = j + 2 * rows - 2;}}else{int j = i;int tmp = (rows - i - 1) * 2;while (j<len){res.push_back(str[j]);if (j + tmp<len)res.push_back(str[j + tmp]);j = 2 * rows + j - 2;}}}return res;}int main(){string str = "PAYPALISHIRING";int rows = 5;string res = ZigZagCon(str, rows);cout << res << endl;}



原创粉丝点击