🔗 🟢 3884. First Matching Character From Both Ends

Problem Statement

題目簡述

給定一個長度為 nn、由小寫英文字母組成的字串 ss。
回傳最小的索引 ii,使得 s[i]=s[n−i−1]s[i] = s[n - i - 1];若不存在則回傳 −1-1。

Constraints

約束條件

  • 1≤n=s.length≤1001 \le n = s.\text{length} \le 100
  • ss 僅包含小寫英文字母

思路:雙指標對稱枚舉

條件 s[i]=s[n−i−1]s[i] = s[n - i - 1] 對索引 ii 與其對稱位置 n−i−1n - i - 1 是對稱的:只要這組配對成立,較小的那個索引一定落在前半段,也就是 0≤i≤⌊n/2⌋0 \le i \le \lfloor n / 2 \rfloor。

關鍵觀察

只需要用 雙指標(Two Pointers) 的想法從左端 i=0i = 0 枚舉到 ⌊n/2⌋\lfloor n / 2 \rfloor,第一個滿足 s[i]=s[n−i−1]s[i] = s[n - i - 1] 的位置就是最小答案。

特別注意 nn 為奇數的情況:當 i=⌊n/2⌋i = \lfloor n / 2 \rfloor 時,對稱位置 n−i−1n - i - 1 恰好等於 ii 本身,因此 s[i]=s[n−i−1]s[i] = s[n - i - 1] 必然成立,迴圈範圍取到 range(n // 2 + 1) 即可自然涵蓋中心字元;若 nn 為偶數,多檢查一次中間交錯位置也不影響正確性。若整段掃描結束仍未找到匹配,回傳 −1-1。

複雜度分析

  • 時間複雜度:O(n)\mathcal{O}(n),最多檢查 ⌊n/2⌋+1\lfloor n / 2 \rfloor + 1 組對稱字元。
  • 空間複雜度:O(1)\mathcal{O}(1),僅使用常數額外變數。

Code

1
2
3
4
5
6
7
8
class Solution:
def firstMatchingIndex(self, s: str) -> int:
# return next((i for i in range(len(s) // 2 + 1) if s[i] == s[len(s) - i - 1]), -1)
n = len(s)
for i in range(n // 2 + 1):
if s[i] == s[n - i - 1]:
return i
return -1

寫在最後

Cover Image Credit

The cover image was created by @D.DCCK. All rights belong to the original artist.

If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.