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

LeetCode 647: Palindromic Substrings

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

基本資料
#

難易度: medium 第一次嘗試:2022-11-01

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

解題思路
#

跟 LC 5 一樣用中心擴展,2n - 1 個中心(字元和字元之間),往外擴的每一步只要兩端相同,就多了一個回文子字串。

我的嘗試
#

一次 AC,跟 LC 5 一樣用奇數、偶數兩個中心各擴展一次。

正確解法
#

class Solution:
    def countSubstrings(self, s: str) -> int:
        count = 0
        for center in range(2 * len(s) - 1):
            l, r = center // 2, center // 2 + center % 2
            while l >= 0 and r < len(s) and s[l] == s[r]:
                count += 1
                l, r = l - 1, r + 1
        return count

複雜度
#

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

要特別避免的錯誤
#

  • 奇數和偶數長度的中心都要算。

面試口說整理
#

我用中心擴展,每個字元和每兩個字元之間都當成中心,往外擴的每一步兩端相同就多一個回文子字串。時間 O(n²)、空間 O(1)。

相關文章

LeetCode 5: Longest Palindromic Substring
·1 分鐘
LeetCode Medium Two-Pointers String Dynamic-Programming Manacher
LeetCode 5 解題筆記:中心擴展,每個位置當奇數和偶數長度的中心往外擴;區間 DP 的話 i 要從大到小
LeetCode 131: Palindrome Partitioning
·1 分鐘
LeetCode Medium String Dynamic-Programming Backtracking
LeetCode 131 解題筆記:每一層從剩下字串的開頭切出一段回文,切的長度從 1 到整段都要試
LeetCode 392: Is Subsequence
·1 分鐘
LeetCode Easy Two-Pointers String Dynamic-Programming
LeetCode 392 解題筆記:兩個指針,t 的指針一直往前,對上 s 的字元時 s 的指針也前進;兩邊的邊界都要檢查
LeetCode 143: Reorder List
·1 分鐘
LeetCode Medium Linked-List Two-Pointers Stack Recursion
LeetCode 143 解題筆記:找中點、反轉後半段、兩條交錯合併;前半段的尾巴要切斷
LeetCode 208: Implement Trie (Prefix Tree)
·1 分鐘
LeetCode Medium Hash-Table String Design Trie
LeetCode 208 解題筆記:每個節點是 children 字典加一個 is_end 標記;insert、search、startsWith 都是沿著字元往下走
LeetCode 287: Find the Duplicate Number
·1 分鐘
LeetCode Medium Array Two-Pointers Binary-Search Bit-Manipulation
LeetCode 287 解題筆記:把 i -> nums[i] 看成鏈結串列,重複的值就是環的入口,用 Floyd 判圈;O(1) 空間、不改陣列