5. Longest Palindromic Substring

Medium

Given a string s, return the longest palindromic substring in s.

Example 1:

Input: s = "babad"
Output:
 "bab"
Explanation:
 "aba" is also a valid answer.

Example 2:

Input: s = "cbbd"
Output:
 "bb"

Constraints:

  • 1 <= s.length <= 1000

  • s consist of only digits and English letters.

解題

func longestPalindrome(s string) string {
	result := ""
	for i := 0; i < len(s); i++ {
		odd := expandAroundCenter(s, i, i)
		even := expandAroundCenter(s, i, i+1)

		if len(odd) > len(result) {
			result = odd
		}
		if len(even) > len(result) {
			result = even
		}
	}

	return result
}

func expandAroundCenter(s string, left int, right int) string {
	l := left
	r := right
	for l >= 0 && r < len(s) && s[l] == s[r] {
		l--
		r++
	}
	return s[l+1 : r]
}

Last updated