Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 5 · Palindrome / Expand Around Center

Longest Palindromic Substring

LeetCode 5 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Expand around centre: odd (i, i) and even (i, i+1).

நடுத்தரம்Two PointersStringDynamic ProgrammingManacher
LeetCode இல் திற ↗

நான் Longest Palindromic Substring (LeetCode 5) ஐ இப்படித் தீர்த்தேன் — Palindrome / Expand Around Center பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Every palindrome mirrors around a centre — either one character (odd length) or the gap between two (even length). Try each of the 2n-1 centres and expand outwards while the ends match; keep the longest.

Approach

  1. 1

    expand_both_side(l, r) grows while s[l] == s[r] and returns the palindrome.

  2. 2

    For each index, expand an odd centre and an even centre.

  3. 3

    Keep whichever palindrome is longest.

நான் எப்படித் தீர்த்தேன்

Expand around centrePythonO(n²) time · O(1) space
class Solution:
    def longestPalindrome(self, s: str) -> str:
        def expand_both_side(s,l,r):
            while l>=0 and r<len(s):
                if s[l]!=s[r]:
                    break
                l-=1
                r+=1
            return s[l+1:r]
        max_len = 0
        max_string = ""
        for i in range(len(s)):
            str1 = expand_both_side(s,i,i)
            if len(str1)>max_len:
                max_len=len(str1)
                max_string=str1
            str2 = expand_both_side(s,i,i+1)
            if len(str2)>max_len:
                max_len=len(str2)
                max_string=str2
        return max_string
            

ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Longest Palindromic Substring — அடிக்கடி கேட்கப்படும் கேள்விகள்

Longest Palindromic Substring பின்னாலுள்ள intuition என்ன?

Every palindrome mirrors around a centre — either one character (odd length) or the gap between two (even length). Try each of the 2n-1 centres and expand outwards while the ends match; keep the longest.

Longest Palindromic Substring (LeetCode 5) ஐ எப்படித் தீர்ப்பது?

1. expand_both_side(l, r) grows while s[l] == s[r] and returns the palindrome. 2. For each index, expand an odd centre and an even centre. 3. Keep whichever palindrome is longest.

Longest Palindromic Substring இன் time மற்றும் space complexity என்ன?

Time: O(n²). Space: O(1). (Accepted approach: Expand around centre.)

Longest Palindromic Substring இல் பொதுவான தவறுகள் என்ன?

Forgetting the even centre misses answers like 'bb'. After the loop, the palindrome is s[l+1:r] — the loop overshoots by one on each side.