Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit987ad0a

Browse files
authored
Create: 0006-zigzag-conversion.cpp
1 parentd69cd3d commit987ad0a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎cpp/0006-zigzag-conversion.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
classSolution {
8+
public:
9+
stringconvert(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+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp