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.