-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathzigzag-conversion.cpp
133 lines (107 loc) · 2.42 KB
/
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
class Solution {
public:
string convert(string s, int numRows) {
vector<vector<int>> list(numRows);
vector<int> index;
int currentIndex = 0;
// Update index
// in case 3
// 0 1 2 1
auto updateIndex = [&]() {
for( int i = 0; i < numRows; i++) {
index.push_back(i);
}
for( int i = numRows - 2; i > 0; i--) {
index.push_back(i);
}
};
updateIndex();
auto getIndex = [&](int i) -> int {
int returnIndex = i % index.size();
return index[returnIndex];
};
for( int i = 0; i< s.size(); i++) {
char current = s[i];
list[getIndex(i)].push_back(current);
}
string st = "";
for( int i = 0; i < numRows; i++) {
for (char a: list[i]) {
st+=a;
}
}
return st;
}
};
// Second
#include <bits/stdc++.h>
#define _DEBUG
#define ll long long
#define pb push_back
#define REP(i, n) for (int i = 0; i < (int)n; i++)
#define pr(i) cout << endl \
<< "...." << i << "...." << endl;
using namespace std;
void solve()
{
string s;
int numOfRows;
cin>>numOfRows;
cin>>s;
vector<vector<char>> rows(numOfRows);
bool flip=false;
int index=0;
numOfRows--;
for(int i=0;s[i];i++){
index=i%(numOfRows);
index=flip?numOfRows-index:index;
// cout<<index<<endl;
if(index==numOfRows-1){
flip=!flip;
}
rows[index].push_back(s[i]);
}
for(int i=0;i<rows.size();i++){
for(int j=0;rows[i][j];j++){
cout<< rows[i][j] << " ";
}
cout<<"\n";
}
}
int main()
{
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int tt = clock();
#endif
int no_of_test_cases;
cin >> no_of_test_cases;
// no_of_test_cases=1;
while (no_of_test_cases--)
{
solve();
}
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
return 0;
}
// Another
class Solution {
public:
string convert(string s, int numRows) {
if(numRows==1) return s;
vector<string> rows(numRows);
int cur=0,fac=1;
string ans;
for(int i=0;i<s.length();i++){
rows[cur].push_back(s[i]);
cur+=fac;
if(cur==0 || cur==numRows-1) fac*=-1;
}
for(auto str: rows) ans+= str;
return ans;
}
};