6. Zigzag Conversion Medium

@problem@discussion
#String



1/**
2 * [6] ZigZag Conversion
3 *
4 * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of 
5 * rows like this: (you may want to display this pattern in a fixed font for better legibility)
6 * 
7 * P   A   H   N
8 * A P L S I I G
9 * Y   I   R
10 * 
11 * And then read line by line: "PAHNAPLSIIGYIR"
12 * Write the code that will take a string and make this conversion given a number of rows:
13 * 
14 * string convert(string s, int numRows);
15 * 
16 *  
17 * Example 1:
18 * 
19 * Input: s = "PAYPALISHIRING", numRows = 3
20 * Output: "PAHNAPLSIIGYIR"
21 * 
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 * 
32 * Example 3:
33 * 
34 * Input: s = "A", numRows = 1
35 * Output: "A"
36 * 
37 *  
38 * Constraints:
39 * 
40 * 1 <= s.length <= 1000
41 * s consists of English letters (lower-case and upper-case), ',' and '.'.
42 * 1 <= numRows <= 1000
43 * 
44 */
45pub struct Solution {}
46
47// problem: https://leetcode.com/problems/zigzag-conversion/
48// discuss: https://leetcode.com/problems/zigzag-conversion/discuss/?currentPage=1&orderBy=most_votes&query=
49
50// submission codes start here
51
52impl Solution {
53    pub fn convert(s: String, num_rows: i32) -> String {
54        if num_rows == 1 {
55            return s.clone();
56        }
57        let mut buff: Vec<Vec<char>> = vec![vec![]; num_rows as usize];
58        let chs: Vec<char> = s.chars().collect();
59        let mut i = 0;
60        while i < s.len() {
61            for down in 0..num_rows {
62                buff[down as usize].push(chs[i]);
63                i += 1;
64                if i >= s.len() {break}
65            }
66            if i >= s.len() {break}
67            for up in 1..num_rows - 1 {
68                buff[(num_rows - up - 1) as usize].push(chs[i]);
69                i += 1;
70                if i >= s.len() {break}
71            }
72        }
73
74        buff.iter().map(|b| {
75            let i = b.into_iter();
76            let x = i.collect::<String>();
77            x
78        }).collect()
79    }
80}
81
82// submission codes end
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn test_6() {
90        assert_eq!(Solution::convert("PAYPALISHIRING".to_string(), 3), "PAHNAPLSIIGYIR".to_string());
91        assert_eq!(Solution::convert("E".to_string(), 3), "E".to_string());
92        assert_eq!(Solution::convert("E".to_string(), 1), "E".to_string());
93        assert_eq!(Solution::convert("PAYPALISHIRING".to_string(), 113), "PAYPALISHIRING".to_string());
94    }
95}
96


Back
© 2025 bowen.ge All Rights Reserved.