Palindromic Substrings
LeetCode 647 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Count expansions from 2n-1 centres.
నేను Palindromic Substrings (LeetCode 647) ను ఇలా పరిష్కరించాను — Palindrome / Interval DP ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Every palindromic substring has a centre. Expanding from each centre, every successful step outward is one more palindrome — so count steps instead of tracking strings.
Approach
- 1
expand_both_side returns how many palindromes share this centre.
- 2
Sum over odd centres (i, i) and even centres (i, i+1).
నేను ఎలా పరిష్కరించాను
Expand around centrePythonO(n²) time · O(1) space
class Solution:
def countSubstrings(self, s: str) -> int:
#expand both side
def expand_both_side(s,start,end):
count = 0
while start>=0 and end<len(s):
if s[start]!=s[end]:
break
count+=1
start-=1
end+=1
return count
count=0
for i in range(len(s)):
count+=expand_both_side(s,i,i)
count+=expand_both_side(s,i,i+1)
return count
Palindromic Substrings — తరచూ అడిగే ప్రశ్నలు
Palindromic Substrings వెనుక ఉన్న intuition ఏమిటి?
Every palindromic substring has a centre. Expanding from each centre, every successful step outward is one more palindrome — so count steps instead of tracking strings.
Palindromic Substrings (LeetCode 647) ను ఎలా పరిష్కరించాలి?
1. expand_both_side returns how many palindromes share this centre. 2. Sum over odd centres (i, i) and even centres (i, i+1).
Palindromic Substrings యొక్క time, space complexity ఎంత?
Time: O(n²). Space: O(1). (Accepted approach: Expand around centre.)
Palindromic Substrings లో సాధారణ పొరపాట్లు ఏమిటి?
Count every expansion, not just the longest one.