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

LeetCode 3884: First Matching Character From Both Ends

·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 第一次嘗試:2026-03-29

  • 提交紀錄:Accepted(一次通過)

解題思路
#

找最小的 i,使得 s[i] == s[n - 1 - i]。從 i = 0 開始往中間檢查,第一個符合的就是答案。

只需要檢查到中間:i 超過中間之後,(i, n - 1 - i) 這一對已經在前面檢查過了。

觀察:長度是奇數時,中間那個字元跟自己比,一定相等,所以奇數長度一定有答案;只有偶數長度才可能回傳 -1。

我的解法
#

class Solution:
    def firstMatchingIndex(self, s: str) -> int:
        n = len(s)
        for i in range((n + 1) // 2):
            if s[i] == s[n - 1 - i]:
                return i
        return -1

原本的版本迴圈跑到 n,結果一樣(找不到時後半段只是重複檢查同樣的 pair),這裡只跑到中間。

複雜度
#

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

要特別避免的錯誤
#

  • 迴圈只跑到 n // 2:奇數長度時會漏掉中間那個字元。

面試口說整理
#

我從 i = 0 往中間檢查 s[i] 和 s[n - 1 - i],第一個相等的就是答案,只需要檢查到中間,因為後半段的 pair 前面都看過了。奇數長度時中間字元一定和自己相等,所以只有偶數長度可能找不到。時間 O(n)。

相關文章

LeetCode 3823: Reverse Letters Then Special Characters in a String
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 3823 解題筆記:兩次對撞指針,第一次只交換字母,第二次只交換特殊字元
LeetCode 2697: Lexicographically Smallest Palindrome
·1 分鐘
LeetCode Easy Two-Pointers String Greedy
LeetCode 2697 解題筆記:對撞指針,兩端不同時都改成比較小的那個字元
LeetCode 3794: Reverse String Prefix
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 3794 解題筆記:切片一行解決;手寫雙指針時要先把字串轉成 list
LeetCode 3750: Minimum Number of Flips to Reverse Binary String
·1 分鐘
LeetCode Easy Two-Pointers Bit-Manipulation String
LeetCode 3750 解題筆記:把二進位字串跟它的反轉逐位比較,不同的位數就是答案
LeetCode 2000: Reverse Prefix of Word
·1 分鐘
LeetCode Easy Two-Pointers String Stack
LeetCode 2000 解題筆記:找到 ch 第一次出現的位置 i,把 word[:i + 1] 反轉接上後面;找不到就原樣回傳
LeetCode 942: DI String Match
·1 分鐘
LeetCode Easy Array Two-Pointers String Greedy
LeetCode 942 解題筆記:兩個指標分別指向還沒用的最小值和最大值,遇到 I 放最小、遇到 D 放最大