leetcode
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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1) return s;
if(numRows >= s.length()) return s;
char t[s.length() + 1] = {0};
int j = 0, index = 0;
while(j < numRows){
if(j == 0){// the first line
for(int i = 0; 2*i * (numRows - 1) < s.length(); i++){
t[index++] = s[2 * i * (numRows - 1)];
}
}
else if(j == numRows - 1){// the last line
for(int i = 0; (2 * i + 1) * (numRows - 1) < s.length(); i++){
t[index++] = s[(2 * i + 1) * (numRows - 1)];
}
}
else{
for(int i = 0; (2 * i * (numRows -1) - j) < s.length() || (2 * i * (numRows -1) + j) < s.length(); i++){
if(((2 * i) * (numRows -1) - j) < s.length() && ((2 * i) * (numRows -1) - j) >= 0){
t[index++] = s[(2 * i) * (numRows -1) - j];
}
if(s[2 * i * (numRows -1) + j] != '\0' && (2 * i * (numRows -1) + j) < s.length()){
t[index++] = s[2 * i * (numRows -1) + j];
}
}
}
j++;
}
return string(t);
}
};
傻瓜方法的思路是创建一个结果字符串,和输入字符串一样长。然后根据输入字符串以及行数(numRows)来填充结果字符串。用变量j来处理每一行,画成之字型之后的每一行。第一行和最后一行单独处理。