iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

LeetCode 每日一題挑戰系列 第 6

Day 5 - Zigzag Conversion

  • 分享至 

  • xImage
  •  

今天要挑戰的是一題字串處理題:Zigzag Conversion。
題目說要把字串照「之字形」排列,最後再把每一列讀出來。

題目範例

Input: "PAYPALISHIRING", numRows = 3
Zigzag 排列:

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

Output: "PAHNAPLSIIGYIR"

Input: "PAYPALISHIRING", numRows = 4

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

Output: "PINALSIGYAHRPI"

Input: "A", numRows = 1
Output: "A"

解題方向

直觀做法就是:

準備一個 StringBuilder[] 陣列,對應每一列。

模擬走路:

一開始往下走,把字元丟到對應的列。

走到最後一列就往上走,再繼續。

重複直到字串走完。

最後把所有列的字串拼起來。

時間複雜度是 O(n),因為只掃過字串一次。

Java 程式碼
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1 || s.length() <= numRows) {
return s;
}

    StringBuilder[] rows = new StringBuilder[numRows];
    for (int i = 0; i < numRows; i++) {
        rows[i] = new StringBuilder();
    }

    int curRow = 0;
    boolean goingDown = false;

    for (char c : s.toCharArray()) {
        rows[curRow].append(c);
        // 遇到頂或底,方向要反轉
        if (curRow == 0 || curRow == numRows - 1) {
            goingDown = !goingDown;
        }
        curRow += goingDown ? 1 : -1;
    }

    StringBuilder result = new StringBuilder();
    for (StringBuilder row : rows) {
        result.append(row);
    }

    return result.toString();
}

}

小心得

這題其實不像一開始看起來那麼複雜,重點是「模擬 Zigzag 的走法」。
寫程式時只要抓到規律:到底 → 往上走;到頂 → 往下走,就能順利解決。https://ithelp.ithome.com.tw/upload/images/20250919/20169537NHN6qLBT3u.pnghttps://ithelp.ithome.com.tw/upload/images/20250919/201695372lajGTG8Ke.pnghttps://ithelp.ithome.com.tw/upload/images/20250919/201695371lzzhEjUeH.pnghttps://ithelp.ithome.com.tw/upload/images/20250919/20169537FSDw5u2K6G.png


上一篇
Day 4 - Longest Palindromic Substring
下一篇
7. Reverse Integer
系列文
LeetCode 每日一題挑戰9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言