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 <= 1000s consist of only digits and English letters.- class Solution {
- public String longestPalindrome(String s) {
- int[] result = new int[2]; // To hold the start and maxLen. 这里不用全局变量了。
-
- for (int i = 0; i < s.length(); i++) {
- // Find the longer palindrome for both odd and even lengths
- int[] oddPalindrome = helper(i, i, s); // case like aba
- int[] evenPalindrome = helper(i, i + 1, s); //case like abba
-
- if (oddPalindrome[1] > result[1]) { //比maxLen大才更新
- result = oddPalindrome;
- }
- if (evenPalindrome[1] > result[1]) {
- result = evenPalindrome;
- }
- }
-
- return s.substring(result[0], result[0] + result[1]);
- }
-
- private int[] helper(int left, int right, String s) {
- while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
- left--;
- right++;
- }
- // Return the start index and length of the palindrome
- return new int[] { left + 1, right - left - 1 };
- }
- }