1. 程式人生 > >ZigZag Conversion——LeetCode進階路⑥

ZigZag Conversion——LeetCode進階路⑥

原題連結https://leetcode.com/problems/zigzag-conversion/

沒開始看題目時,小陌發現這道題似乎備受嫌棄,被n多人踩了,還有點小同情

  • 題目描述

    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
  • 思路分析:
    題目需求是把輸入字元排成鋸齒牙子,再按行進行輸出
    至於鋸齒牙子啥樣,沒腦補出來的猿兄們看eg:
    Input: s = "123456789", numRows = 2
    1 3 5 7 9
    2 4 6 8

Output: "135792468"
Input: s = "123456789", numRows = 3
1     5   9
2  4 6 8
3     7

Output: "159246837"
Input: s = "123456789", numRows = 4
1       7
2    6 8
3 5    9
4


Output: "172683594"
恭喜猿兄,你已經把這道題中“最難”的部分搞定了,如你所見,除了題意相對難理解之外,剩下的簡直就是數學的找規律問題
爾後猿兄也發現阿六為啥被踩了叭~
規律分析:(方便起見,n=numRows)

         
首尾兩行元素之間的間隔interval1 = 2n-2

兩者之間的行中元素的間隔interval = 前一元素的列數 + interval1 - 2 * 當前行數

  • 原始碼附錄
    class Solution {
        public String convert(String s, int numRows) {
            if(s == null||numRows<=0){
                return "";
            }
            if(s.length()<2||numRows<2){
                return s;
            }
            
            int interval = 2*numRows - 2;
            int interval1;
            StringBuilder sb = new StringBuilder();
            for(int i=0;i<numRows;i++){
                for(int j=i;j<s.length();j=j+interval){
                    sb.append(s.charAt(j));
                    if(i != 0&&i != numRows-1){
                        interval1 = j + interval - 2*i;
                        if(interval1 < s.length()){
                            sb.append(s.charAt(interval1));
                        }
                    }
                }
            }
            return sb.toString();
        }
    }