Description
The string "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 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)
And then read line by line:"AIQYBHJPRXZCGKOSWDFLNTVEMU"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 5) should return "AIQYBHJPRXZCGKOSWDFLNTVEMU".
Solution
细节题目,遍历s,将字符s[i] append到对应字符串中即可,最终遍历字符串数组求解
string convert(string s, int numRows) {
if (numRows == 1 || s.length() <= 1) {
return s;
}
int rowSize = 2 * numRows - 2;
string strConverted = "";
vector<string> strRows(numRows, "");
for (int i = 0; i < s.length(); ++i) {
int remain = i%(rowSize);
remain = (remain<numRows? remain : rowSize-remain);//如果是斜边,需要重新计算index
strRows[remain] = strRows[remain] + s[i];
}
for (int j = 0; j < numRows; ++j) {
strConverted += strRows[j];
}
return strConverted;
}