↓快轉到主要內容
  1. LeetCode/

LeetCode 344: Reverse String

·1 分鐘· ·
LeetCode Easy Two-Pointers String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-23

  • 提交紀錄:Accepted ×2 → Runtime Error → Accepted

解題思路
#

左右指針交換、往中間走,直到相遇(Two Pointers 模板一)。

我的嘗試
#

2026 年重寫時一版右指針從 len(s) 開始,超出範圍。

正確解法
#

class Solution:
    def reverseString(self, s: List[str]) -> None:
        l, r = 0, len(s) - 1
        while l < r:
            s[l], s[r] = s[r], s[l]
            l, r = l + 1, r - 1

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 右指針從 len(s) - 1 開始。

面試口說整理
#

我用左右指針交換兩端再往中間走,原地反轉。時間 O(n)、空間 O(1)。

相關文章

LeetCode 392: Is Subsequence
·1 分鐘
LeetCode Easy Two-Pointers String Dynamic-Programming
LeetCode 392 解題筆記:兩個指針,t 的指針一直往前,對上 s 的字元時 s 的指針也前進;兩邊的邊界都要檢查
LeetCode 125: Valid Palindrome
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 125 解題筆記:左右指針跳過非英數字元,再比較小寫是否相同;數字也要算進去
LeetCode 28: Find the Index of the First Occurrence in a String
·1 分鐘
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 解題筆記:在每個起點比對 needle,或直接用 str.find;index 找不到會丟例外
LeetCode 345: Reverse Vowels of a String
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 345 解題筆記:跟 LC 917 一樣的左右指針,只是條件換成「是不是母音」(大小寫都要算)
LeetCode 283: Move Zeroes
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 283 解題筆記:寫入指標只在遇到非零數時前進,跟它交換;零自然被推到後面
LeetCode 290: Word Pattern
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 290 解題筆記:pattern 的字元和單字要一對一對應,用兩個方向的 dict 或比較 set 大小