week4-leetcode #6-ZigZag Conversion[Medium]
题目链接:https://leetcode.com/problems/zigzag-conversion/description/
Question
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 text, int nRows);
convert("PAYPALISHIRING", 3)
should return
"PAHNAPLSIIGYIR"
Solution1[base]
time complecity: O(n∗m)
space complecity: O(n∗m)
其中m代表字符串s的长度,n代表行的大小
runtime:85ms
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
int numCols = s.length();
char** myMatrix = initMatrix(numRows, numCols);
myMatrix = fillInMatrix(myMatrix, numRows, numCols, s);
string out = readMatrix(myMatrix, numRows, numCols);
for (int i = 0; i < numRows; i++) {
delete myMatrix[i];
}
delete myMatrix;
return out;
}
char** initMatrix(int numRows, int numCols) {
char** myMatrix = new char*[numRows];
for (int i = 0; i < numRows; i++) {
myMatrix[i] = new char[numCols]();
}
for (int i = 0 ; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
myMatrix[i][j] = ' ';
}
}
return myMatrix;
}
char** fillInMatrix(char** myMatrix, int numRows, int numCols, string s) {
int indexOfS = 0;
int colIndex = 0;
int rowIndex = -1;
int termLength = 2*numRows-2;
int currentLength = 0;
int length = s.length();
while(indexOfS < length) {
if (currentLength < numRows) {
rowIndex++;
myMatrix[rowIndex][colIndex] = s[indexOfS];
} else {
rowIndex--;
colIndex++;
myMatrix[rowIndex][colIndex] = s[indexOfS];
}
currentLength++;
if (currentLength == termLength) {
currentLength = 0;
rowIndex = -1;
colIndex++;
}
// 字符串填满
indexOfS++;
if (indexOfS == length)
break;
}
return myMatrix;
}
string readMatrix(char** myMatrix, int numRows, int numCols) {
string out = "";
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
if (myMatrix[row][col] != ' ') {
out += myMatrix[row][col];
}
}
}
return out;
}
};
思路:构建一个二维数组,将字符串按照ZigZag的规则放入该数组,最后按照每行的顺序去读取数组即可。这里比较复杂的是实现ZigZag规则,ZigZag规则是按照一定的顺序来排列字符。
ZigZag规则
n = 1
1 2 3 4 5
n = 2
1 3 5 7 9
2 4 6 8 10
n = 3
1 5 9
2 4 6 8 10
3 7
n = 4
1 7 13
2 6 8 12 14
3 5 9 11 15
4 10 16