Skip to content

Commit d27c937

Browse files
committed
leetcode
1 parent 0eff8bc commit d27c937

File tree

4 files changed

+91
-0
lines changed

4 files changed

+91
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ This repo contain leetcode solution using DART and GO programming language. Most
202202
- [**1626.** Best Team With No Conflicts](BestTeamWithNoConflicts/best_team_with_no_conflicts.dart)
203203
- [**1071.** Greatest Common Divisor of Strings](GreatestCommonDivisorOfStrings/greatest_common_divisor_of_strings.dart)
204204
- [**953.** Verifying an Alien Dictionary](VerifyingAnAlienDictionary/verifying_an_alien_dictionary.dart)
205+
- [**6.** Zigzag Conversion](ZigzagConversion/zigzag_conversion.dart)
205206

206207
## Reach me via
207208

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
3+
4+
-* 6. Zigzag Conversion *-
5+
6+
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)
7+
8+
P A H N
9+
A P L S I I G
10+
Y I R
11+
And then read line by line: "PAHNAPLSIIGYIR"
12+
13+
Write the code that will take a string and make this conversion given a number of rows:
14+
15+
string convert(string s, int numRows);
16+
17+
18+
Example 1:
19+
20+
Input: s = "PAYPALISHIRING", numRows = 3
21+
Output: "PAHNAPLSIIGYIR"
22+
Example 2:
23+
24+
Input: s = "PAYPALISHIRING", numRows = 4
25+
Output: "PINALSIGYAHRPI"
26+
Explanation:
27+
P I N
28+
A L S I G
29+
Y A H R
30+
P I
31+
Example 3:
32+
33+
Input: s = "A", numRows = 1
34+
Output: "A"
35+
36+
37+
Constraints:
38+
39+
1 <= s.length <= 1000
40+
s consists of English letters (lower-case and upper-case), ',' and '.'.
41+
1 <= numRows <= 1000
42+
43+
*/
44+
class A {
45+
String convert(String s, int numRows) {
46+
if (numRows == 1) return s;
47+
List<String> rows = List.filled(numRows, "");
48+
int j = 0, d = 1;
49+
for (int i = 0; i < s.length; i++) {
50+
rows[j] += s[i];
51+
if (j == numRows - 1)
52+
d = -1;
53+
else if (j == 0) d = 1;
54+
j += d;
55+
}
56+
57+
String res = "";
58+
for (int i = 0; i < numRows; i++) {
59+
res += rows[i];
60+
}
61+
62+
return res;
63+
}
64+
}

ZigzagConversion/zigzag_conversion.go

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package main
2+
3+
import "bytes"
4+
5+
func convert(s string, numRows int) string {
6+
if numRows == 1 {
7+
return s
8+
}
9+
rows := make([][]byte, numRows)
10+
curRow, step := 0, 1
11+
for i := range s {
12+
rows[curRow] = append(rows[curRow], s[i])
13+
curRow += step
14+
if curRow == 0 {
15+
step = 1
16+
} else if curRow == numRows-1 {
17+
step = -1
18+
}
19+
}
20+
21+
var res bytes.Buffer
22+
for i := range rows {
23+
res.Write(rows[i])
24+
}
25+
return res.String()
26+
}

ZigzagConversion/zigzag_conversion.md

Whitespace-only changes.

0 commit comments

Comments
 (0)