-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzigzagConversion.cpp
More file actions
63 lines (61 loc) · 1.55 KB
/
Copy pathzigzagConversion.cpp
File metadata and controls
63 lines (61 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* https://leetcode.com/problems/zigzag-conversion/
* String
* Medium
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
void updateMatrix(char letter, vector<vector<char> >& matrix, int numRows, int numCols, int& i, int& j, char& lastDir) {
matrix[i][j] = letter;
//cout << i << ' ' << j << ' ' << letter << endl;
if (i == 0) {
lastDir = 'd';
}
else if (i == numRows - 1) {
lastDir = 'u';
}
if (lastDir == 'd') {
i++;
} else {
i--;
j++;
}
}
string convert(string s, int numRows) {
if (numRows == 1) {
return s;
}
int numCols = s.size();
vector<vector<char> > matrix(numRows, vector<char>(numCols));
int i = 0, j = 0;
char lastDir = 'd';
for (int pos = 0; pos < numCols; pos++) {
updateMatrix(s[pos], matrix, numRows, numCols, i, j, lastDir);
}
string zigzag;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (matrix[i][j] == '\0') {
continue;
}
zigzag += matrix[i][j];
}
}
return zigzag;
}
};
int main() {
string s;
int numRows;
cout << "Input string: ";
cin >> s;
cout << "Input number of rows: ";
cin >> numRows;
Solution solution;
string zigzag = solution.convert(s, numRows);
cout << zigzag << endl;
}