用 Rust 刷 leetcode 第六题

Problem

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);

Example

Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

Solution

impl Solution {
    pub fn convert(s: String, num_rows: i32) -> String {
        if num_rows < 2 {
            return s;
        }
        let seq: Vec<char> = s.chars().collect();
        let len = seq.len();

        let num_rows: usize = num_rows as usize;
        let mut i: usize = 0;
        let mut j: usize = 0;
        let mut step: usize = 0;
        let mut row: usize = 0;
        let mut down_flag: bool = true;
        let mut result = String::with_capacity(s.capacity());

        while i < len {
            result.push(seq[j]);
            i += 1;

            if ((row == 0) || (row == (num_rows-1)))
            {
                step = 2*num_rows-2;
            } else {
                if (down_flag)
                {
                    step = 2*(num_rows-row)-2;
                    down_flag = false;
                } else {
                    step = 2*(row+1) - 2;
                    down_flag = true;
                }
            }

            j += step;
            if (j >= len)
            {
                row += 1;
                j = row;
                down_flag = true;
            }
        }

        result
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商