Skip to content

Commit 4f852c7

Browse files
Update and rename ZigzagConversion.cpp to medium-6-zigzag_conversion.cpp
1 parent 39ae428 commit 4f852c7

File tree

2 files changed

+55
-21
lines changed

2 files changed

+55
-21
lines changed

Codes/ZigzagConversion.cpp

Lines changed: 0 additions & 21 deletions
This file was deleted.
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// 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)
2+
3+
// P A H N
4+
// A P L S I I G
5+
// Y I R
6+
7+
// And then read line by line: "PAHNAPLSIIGYIR"
8+
9+
// Write the code that will take a string and make this conversion given a number of rows:
10+
11+
// string convert(string s, int numRows);
12+
13+
14+
// Example 1:
15+
16+
// Input: s = "PAYPALISHIRING", numRows = 3
17+
// Output: "PAHNAPLSIIGYIR"
18+
19+
// Example 2:
20+
21+
// Input: s = "PAYPALISHIRING", numRows = 4
22+
// Output: "PINALSIGYAHRPI"
23+
// Explanation:
24+
// P I N
25+
// A L S I G
26+
// Y A H R
27+
// P I
28+
29+
// Example 3:
30+
31+
// Input: s = "A", numRows = 1
32+
// Output: "A"
33+
34+
35+
class Solution {
36+
public:
37+
string convert(string s, int numRows) {
38+
if(numRows <= 1)
39+
return s;
40+
vector<string>v(numRows, "");
41+
int j = 0, dir = -1;
42+
for(int i = 0; i < s.length(); i++){
43+
if(j == numRows - 1 || j == 0)
44+
dir *= (-1);
45+
v[j] += s[i];
46+
if(dir == 1)
47+
j++;
48+
else j--;
49+
}
50+
string res;
51+
for(auto &it : v)
52+
res += it;
53+
return res;
54+
}
55+
};

0 commit comments

Comments
 (0)