1
+ /*
2
+ The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
3
+ (you may want to display this pattern in a fixed font for better legibility)
4
+
5
+ P A H N
6
+ A P L S I I G
7
+ Y I R
8
+ And then read line by line: "PAHNAPLSIIGYIR"
9
+
10
+ Write the code that will take a string and make this conversion given a number of rows:
11
+
12
+ string convert(string s, int numRows)
13
+
14
+ Input: s = "PAYPALISHIRING", numRows = 3
15
+ Output: "PAHNAPLSIIGYIR"
16
+
17
+ Constraints:
18
+ 1 <= s.length <= 1000
19
+ s consists of English letters (lower-case and upper-case), ',' and '.'.
20
+ 1 <= numRows <= 1000
21
+
22
+ */
23
+
24
+ /*
25
+ Time Complexity: O(N), where N is the length of the array
26
+ Space Complexity: O(N), where N is the length of the array
27
+ */
28
+
29
+ #include < bits/stdc++.h>
30
+ using namespace std ;
31
+
32
+ string convert (string s, int numRows)
33
+ {
34
+ vector<vector<char >> a (numRows); // vector of vector to store character in each rows
35
+ int i = 0 ; // variable to determine in which row we must add particular character
36
+ bool direction = true ; // variable to determine the direction of movement
37
+ for (char ch : s)
38
+ {
39
+ a[i].push_back (ch);
40
+ if (direction == true ) // if direction is down => increment i
41
+ i++;
42
+ if (i == numRows) // if i reached end => reverse the direction and decrement i
43
+ {
44
+ direction = false ;
45
+ i--;
46
+ }
47
+ if (direction == false ) // if direction is up => decrement i
48
+ i--;
49
+ if (i <= 0 ) // if i reached start => reverse the direction and set i to 0
50
+ {
51
+ direction = true ;
52
+ i = 0 ;
53
+ }
54
+ }
55
+
56
+ string str = " " ; // forming the final string to return
57
+ for (vector<char > c : a)
58
+ {
59
+ for (char ch : c)
60
+ str += ch;
61
+ }
62
+ return str;
63
+ }
64
+
65
+ int main () // driver function
66
+ {
67
+ string str = " PAYPALISHIRING" ;
68
+ string ans = convert (str,3 );
69
+ cout << ans;
70
+ return 0 ;
71
+ }
0 commit comments