rust leetcode zigzag-conversion

每日小刷

leetcode

Runtime Memory
16ms 2.5m
use std::cmp;

impl Solution {
pub fn convert(s: String, num_rows: i32) -> String {
        if num_rows == 1 {
            return s;
        }

        let num_rows: usize = cmp::min(s.len(), num_rows as usize);

        let mut zig_zag: Vec = vec![String::from(""); num_rows];

        let text: Vec = s.chars().collect();

        let mut cur_row = 0;
        let mut direction = false;
        for i in 0..text.len() {
            zig_zag[cur_row] = zig_zag[cur_row].clone() + &text[i].to_string();
            
            if cur_row == (num_rows-1) || cur_row == 0{
                direction = !direction;
            }
            if direction {
                cur_row += 1;
            } else {
                cur_row -= 1;
            }
        }
        let mut result = String::from("");

        for elem in zig_zag.iter() {
            result += elem;
        }
        result
    }
}

好好学习rust和基础算法

你可能感兴趣的:(rust leetcode zigzag-conversion)