Longest Palindromic Substring
LeetCode 5 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Expand around centre: odd (i, i) and even (i, i+1).
ನಾನು 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
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.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
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.