美文网首页数据结构和算法
rust leetcode zigzag-conversion

rust leetcode zigzag-conversion

作者: 奔跑的蛙牛 | 来源:发表于2019-11-22 00:19 被阅读0次

    每日小刷

    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<String> = vec![String::from(""); num_rows];
    
            let text: Vec<char> = 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

        本文链接:https://www.haomeiwen.com/subject/jsaxwctx.html