1. 程式人生 > 其它 >LeetCode 6. Z字形變換

LeetCode 6. Z字形變換

技術標籤:刷題

難度:中等。
沒啥技巧,就是找規律。可以從週期來考慮,以下述紅框內的為一個週期。按照這個週期來找更具體地規律。
在這裡插入圖片描述
在這裡插入圖片描述

正確解法:

class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.length();
        if(len < 2 || numRows < 2)return s;
        int midde_num = numRows - 2;
        int z_num = numRows + midde_num;
int period_cols = numRows - 1; int max_cols = len / z_num * period_cols + midde_num + 1; string new_string; for(int row = 0; row < numRows; row++){ for(int col = 0; col < max_cols; col++){ int temp_col = col % period_cols; int
period_num = col / period_cols; if(temp_col == 0){ int index = z_num * period_num + row; if(index < len){ new_string += s[index]; } } else{ int temp =
numRows - row - 1; if(col == period_num * period_cols + temp){ int index = z_num * period_num + numRows + temp - 1; if(index < len){ new_string += s[index]; } } } } } return new_string; } };