Skip to content

Commit e3fb1f1

Browse files
committed
Added Zigzag Conversion
1 parent 01aa8ab commit e3fb1f1

File tree

1 file changed

+40
-6
lines changed

1 file changed

+40
-6
lines changed

src/zigzag_conversion.rs

+40-6
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,38 @@ struct Solution;
1313

1414
impl Solution {
1515

16-
// TODO: Implement
17-
pub fn convert(_s: String, _num_rows: i32) -> String {
18-
"".to_string()
16+
pub fn convert(s: String, num_rows: i32) -> String {
17+
if num_rows <= 1 { s }
18+
else {
19+
let n = num_rows as usize;
20+
let mut down = true;
21+
let mut row = 0;
22+
let mut holding = vec![vec![]; n];
23+
24+
for c in s.chars() {
25+
holding[row].push(c);
26+
if down {
27+
if row == n-1 {
28+
down = false;
29+
row = n-2;
30+
} else {
31+
row += 1;
32+
}
33+
} else {
34+
if row == 0 {
35+
down = true;
36+
row = 1;
37+
} else {
38+
row -= 1;
39+
}
40+
}
41+
}
42+
43+
holding
44+
.iter()
45+
.map(|row| row.iter().collect::<String>())
46+
.collect()
47+
}
1948
}
2049

2150
}
@@ -24,7 +53,6 @@ impl Solution {
2453
mod tests {
2554
use super::Solution;
2655

27-
#[ignore]
2856
#[test]
2957
fn example_1() {
3058
let s = "PAYPALISHIRING".to_string();
@@ -33,7 +61,6 @@ mod tests {
3361
assert_eq!(result, "PAHNAPLSIIGYIR");
3462
}
3563

36-
#[ignore]
3764
#[test]
3865
fn example_2() {
3966
let s = "PAYPALISHIRING".to_string();
@@ -42,7 +69,6 @@ mod tests {
4269
assert_eq!(result, "PINALSIGYAHRPI");
4370
}
4471

45-
#[ignore]
4672
#[test]
4773
fn example_3() {
4874
let s = "A".to_string();
@@ -51,4 +77,12 @@ mod tests {
5177
assert_eq!(result, "A");
5278
}
5379

80+
#[test]
81+
fn two_rows() {
82+
let s = "ABCDEFGHIJKLMNOP".to_string();
83+
let num_rows = 2;
84+
let result = Solution::convert(s, num_rows);
85+
assert_eq!(result, "ACEGIKMOBDFHJLNP");
86+
}
87+
5488
}

0 commit comments

Comments
 (0)