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.