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)
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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
方法1:遍歷每次首行和最后一行改變方向(所為方向就是行++和行--)
class Solution {
public:
string convert(string s, int numRows) {
if (1 >= numRows) {
return s;
}
int length = s.length();
int curRow = 0;
int direct = 1;
string out[numRows];
for(int i = 0; i < length; i++) {
out[curRow] += s[i];
if(0 == curRow) {
direct = 1;
}
if(numRows - 1 == curRow ) {
direct = -1;
}
curRow += direct;
}
string result = "";
for(int i = 0; i < numRows; i++){
result += out[i];
}
return result;
}
};
方法2:分組滨溉,每組行數(shù)*2-2個泼诱,首行和末行各一聋庵,其余各行各2,秩序計(jì)算一下通用公式即可醒第;
class Solution {
public:
string convert(string s, int numRows) {
if (1 >= numRows) {
return s;
}
string out = "";
int length = s.length();
int temp = 2 * numRows -2;
for(int i = 0; i < numRows; i++) {
int curTemp = 0;
while(curTemp * temp + i < length) {
out += s[curTemp * temp + i];
if(0!=i && numRows-1!=i && (curTemp+1)*temp-i<length) {
out += s[(curTemp+1)*temp-i];
}
curTemp++;
}
}
return out;
}
};