leetcode_rust/
zigzag_conversion.rs

1#![allow(dead_code)]
2
3pub fn convert(s: String, num_rows: i32) -> String {
4    use std::iter;
5    let num_rows = num_rows as usize;
6
7    if num_rows == 1 {
8        return s;
9    }
10
11    let mut mat: Vec<Vec<char>> = Vec::with_capacity(num_rows as usize);
12    for _ in 0..num_rows {
13        mat.push(iter::repeat('\0').take(s.len()).collect::<Vec<char>>());
14    }
15
16    let mut step = false;
17    let mut j = 0;
18    let mut char_i = 0;
19    for i in (0..num_rows).chain((1..num_rows - 1).rev()).cycle() {
20        match s.chars().nth(char_i) {
21            Some(c) => mat[i][j] = c,
22            None => {
23                break;
24            }
25        };
26        if i == num_rows - 1 {
27            step = true;
28        }
29        if i == 0 {
30            step = false;
31        }
32
33        if step {
34            j += 1;
35        }
36
37        char_i += 1;
38    }
39
40    // ineffective
41    let mut ret = vec![];
42    for line in mat {
43        for ch in line {
44            if ch != '\0' {
45                ret.push(ch);
46            }
47        }
48    }
49
50    ret.iter().collect::<String>()
51}
52
53pub fn convert2(s: String, num_rows: i32) -> String {
54    if num_rows == 1 {
55        return s;
56    }
57    let num_rows = num_rows as usize;
58    let mut rows: Vec<String> = Vec::with_capacity(usize::min(num_rows, s.len()));
59    for _ in 0..num_rows {
60        rows.push(String::from(""));
61    }
62    let mut cur_row = 0;
63    let mut down = false;
64    for c in s.chars() {
65        rows[cur_row] += &c.to_string();
66        if cur_row == 0 || cur_row == num_rows - 1 {
67            down = !down;
68        }
69        if down {
70            cur_row += 1;
71        } else {
72            cur_row -= 1;
73        }
74    }
75
76    rows.iter().fold(String::from(""), |acc, s| acc + s)
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[test]
84    fn test1() {
85        assert_eq!(
86            convert(String::from("LEETCODEISHIRING"), 3),
87            String::from("LCIRETOESIIGEDHN")
88        );
89        assert_eq!(
90            convert(String::from("LEETCODEISHIRING"), 4),
91            String::from("LDREOEIIECIHNTSG")
92        );
93    }
94
95    #[test]
96    fn test2() {
97        assert_eq!(
98            convert2(String::from("LEETCODEISHIRING"), 3),
99            String::from("LCIRETOESIIGEDHN")
100        );
101        assert_eq!(
102            convert2(String::from("LEETCODEISHIRING"), 4),
103            String::from("LDREOEIIECIHNTSG")
104        );
105    }
106}