File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ For each row the next chracter is at index 2 * (n -1) and
3
+ For middle rows there will be extra characters
4
+ Time: O(n)
5
+ Space: O(1)
6
+ */
7
+ class Solution {
8
+ public:
9
+ string convert (string s, int n) {
10
+ // Edge case
11
+ if (n == 1 ) return s;
12
+ // Other cases
13
+ // Take string to store answer
14
+ string ans = " " ;
15
+ // We are going to traverse each row
16
+ for (int row = 0 ; row < n ; row++){
17
+ // for each row the next chracter is at index 2 * (n -1)
18
+ int increment = 2 * (n -1 );
19
+ // For first and last rows
20
+ for (int i = row; i < s.length (); i+= increment){
21
+ ans += s[i];
22
+ // For middle rows there will be extra characters
23
+ if (row > 0 && row < n-1 && i+increment - 2 * row < s.length ()){
24
+ ans += s[i+increment - 2 * row];
25
+ }
26
+ }
27
+ }
28
+ return ans;
29
+ }
30
+ };
You can’t perform that action at this time.
0 commit comments