用 Rust 刷 leetcode 第六題

linghuyichong發表於2020-01-02

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 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
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 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章