-
Notifications
You must be signed in to change notification settings - Fork 0
/
6_zigzag_conversion.cpp
118 lines (110 loc) · 2.93 KB
/
6_zigzag_conversion.cpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Solution 1: Create a vector 2D to store the characters in each row and column
// Time complexity: O(n)
class Solution_1 {
public:
string convert(string s, int numRows) {
// Check if numRows is 1
if (numRows == 1)
return s;
// Create a vector 2D to store the characters in each row
vector<vector<string>> zigzag(numRows, vector<string>(s.size(), ""));
// Initialize the row and column
int row = 0, col = 0;
// Initialize the direction
bool down = true;
// Iterate through the string
for (int i = 0; i < s.size(); i++) {
// Store the character in the current row and column
zigzag[row][col] = s[i];
// If the direction is down
if (down) {
// If the row is less than numRows - 1
if (row < numRows - 1) {
// Increment the row
row++;
} else {
// Change the direction
down = false;
// Decrement the row
row--;
// Increment the column
col++;
}
} else {
// If the row is greater than 0
if (row > 0) {
// Decrement the row
row--;
// Increment the column
col++;
} else {
// Change the direction
down = true;
// Increment the row
row++;
}
}
}
// Initialize the result
string result = "";
// Iterate through the vector 2D
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < s.size(); j++) {
// If the character is not empty
if (zigzag[i][j] != "") {
// Append the character to the result
result += zigzag[i][j];
}
}
}
// Return the result
return result;
}
};
// Solution 2: Create a vector of strings to store the characters in each row
// Time complexity: O(n)
class Solution_2 {
public:
string convert(string s, int numRows) {
if (numRows == 1)
return s;
vector<string> rows(min(numRows, int(s.size())));
int curRow = 0;
bool goingDown = false;
for (char c : s) {
rows[curRow] += c;
if (curRow == 0 || curRow == numRows - 1)
goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
string ret;
for (string row : rows)
ret += row;
return ret;
}
};
// Solution 3: Use cycle to calculate the row index of each character
// Time complexity: O(n)
class Solution_3 {
public:
string convert(string s, int numRows) {
if (numRows == 1)
return s;
string ret;
int n = s.size();
int cycleLen = 2 * numRows - 2;
for (int i = 0; i < numRows; i++) {
// Iterate through the string to get the cycle characters
for (int j = 0; j + i < n; j += cycleLen) {
ret += s[j + i];
if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
ret += s[j + cycleLen - i];
}
}
return ret;
}
};