LEECODE Algorithm 6. ZigZag Conversion
- 题目
- 代码块
- 想法
Description
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)
Find the median of the two sorted arrays. The overall run time complexity >should be O(log (m+n)).
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”.
代码
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1){
return s;
}
int quotient = s.length()/(2*numRows-2);
int remainder = s.length()%(2*numRows-2);
int numCols = 0;
if(remainder > numRows){
numCols = 1 + remainder - numRows + (numRows - 1)*quotient;
}
else{
numCols = 1 + (numRows - 1)*quotient;
}
char arr[numRows][numCols];
string output = "";
int colcount = 0,down = 1,k = 0;;
for(int i =0; i < numRows; i++){
for(int j = 0; j < numCols; j++){
arr[i][j] = '0';
}
}
for(int i = 0; i < s.length(); i++){
k++;
if(down == 1){
arr[k-1][colcount] = s[i];
}
else{
arr[numRows-k-1][colcount] = s[i];
}
if(down == 0){
colcount++;
}
else{
if(k == numRows){
colcount++;
down = 0;
k = 0;
}
}
if(down == 0 && k == numRows-2){
k = 0;
down = 1;
}
}
for(int i =0; i < numRows; i++){
for(int j = 0; j < numCols; j++){
if(arr[i][j] != '0'){
output += arr[i][j];
}
}
}
return output;
}
};
想法
首先,很明显这一题用矩阵来记录z字型信息,关键是求得矩阵的row,col值。对于n行的z字形,完全的上升部分有n-2个点,占用了n-2列,通过数学知识易得row,col。随后设置一个s.length()次的for循环,设置变量colcount,记录下一次字符应该放的位置,依次,便可得出结果.