LeetCode Z 字形变换 rust

2022-06-22  本文已影响0人  liaozhiyuan
  1. 题目:
    https://leetcode.cn/problems/zigzag-conversion/
    将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
    比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:
P   A   H   N
A P L S I I G
Y   I   R

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);

  1. 思路:

执行用时:4 ms, 在所有 Rust 提交中击败了78.24%的用户
内存消耗:2.2 MB, 在所有 Rust 提交中击败了61.77%的用户
通过测试用例:
1157 / 1157

源码:

use std::cmp::Ordering::*;
#[derive(Debug)]
struct Point {
    alph: char,
    x: i32,
    y: i32,
}

struct ZConvert {
    mid: i32,
    x: i32,
    y: i32,
}

impl ZConvert {
    fn new(row: i32) -> Self {
        ZConvert {
            mid: row - 1,
            x: 0,
            y: 0,
        }
    }
    fn get_next_coordinate(&mut self) -> (i32, i32) {
        if self.mid == 0 {
            self.y += 1;
            return (self.x,self.y)
        }
        let x: i32 = self.x % (2 * self.mid);
        self.x += 1;
        if x < self.mid {
            return (x, self.y);
        } else {
            self.y += 1;
            return (2 * self.mid - x, self.y - 1);
        }
    }
}

impl Solution {
    pub fn convert(s: String, num_rows: i32) -> String {
        let mut z = ZConvert::new(num_rows);
        let mut points = s
            .chars()
            .map(move |alph| {
                let (x, y) = z.get_next_coordinate();
                Point {
                    alph: alph,
                    x: x,
                    y: y,
                }
            })
            .collect::<Vec<Point>>();
          points.sort_by(|p1, p2| {
            if p1.x < p2.x {
                return Less;
            } else if p1.x > p2.x {
                return Greater;
            } else {
                if p1.y > p2.y {
                    return Greater;
                } else if p1.y < p2.y {
                    return Less;
                } else {
                    return Equal;
                }
            }
        });
        return points.into_iter().map(|p| p.alph).collect::<String>();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读