Problem Statement
Given a string s, return the longest palindromic substring in s.
Test Cases
Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
Constraints
1 <= s.length <= 1000
s consist of only digits and English letters.
Code
class Solution {
private int resultStart;
private int resultLength;
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return "";
}
if (s.length() == 1)
return s;
int length = s.length();
for (int start=0; start<length-1; start++) {
widerange(s, start, start);
widerange(s, start, start+1);
}
return s.substring(resultStart, resultStart + resultLength);
}
public void widerange(String s, int start, int end) {
while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
start -= 1;
end += 1;
}
if (resultLength < end - start - 1) {
resultLength = end - start - 1;
resultStart = start + 1;
}
}
}
Top comments (1)
Cool!