Given a string s, return the longest palindromic substring in s.
s = "babad""bab"start=0, maxLen=1 (single char is a palindrome)i, expand odd center (i,i) and even (i,i+1)s[l]==s[r], grow l--, r++; record palindrome lengthmaxLen, update start and maxLenWhy centers? Every palindrome has a center: one character (odd length) or between two characters (even length). Trying all n odd and n−1 even centers covers every substring that can be a palindrome.
Why expand? If s[l..r] is a palindrome and s[l-1]==s[r+1], then s[l-1..r+1] is also a palindrome. We greedily expand until characters differ or we leave the string.
Why O(n²)? O(n) centers × up to O(n) expansion steps each.
Building every substring and checking whether it is a palindrome is O(n) cubed. That is far too slow.
Every palindrome has a center. Treat each index as a center, and expand to both sides while the two ends match. But note that a palindrome like b b has its center between two characters. So expand twice at every index: once from a single character, and once from the gap after it.
Expand around 2 n −1 centers, both odd and even. Keep only the longest expansion.
Run the animation above on your own input, or watch the 1:41 video explanation of Longest Palindromic Substring with a dry run and Java code.