你一个字符串 s
,找到 s
中最长的 回文子串。
示例 1:
输入:s = "babad" 输出:"bab" 解释:"aba" 同样是符合题意的答案。
示例 2:
输入:s = "cbbd" 输出:"bb"
class Solution {
public String longestPalindrome(String s) {
if(s.length()<=1){
return s;
}
int max = 0;
String result = "";
int count = 0;
int bound = 0;
for(int index =0;index<s.length();index++){
count = rightIndex(s,index,index);
if(count>=max && (index-(count-1)/2)<(index+(count-1)/2 + 1)){
max = count;
result = s.substring(index-(count-1)/2,index+(count-1)/2 + 1);
}
count = rightIndex(s,index,index+1);
if(count>=max && (index-(count)/2+1)<(index+(count)/2 + 1)){
max = count;
result = s.substring(index-(count)/2+1,index+(count)/2 + 1);
}
}
return result;
}
/**
0 1 2 3 4 5
*/
public int rightIndex(String s,int left,int right){
int len = s.length();
while(left>=0 && right<len && (s.charAt(left) == s.charAt(right)) ){
left--;
right++;
}
return right-left-1;
}
}
官方相同解法:
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() < 1) {
return "";
}
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
public int expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
--left;
++right;
}
return right - left - 1;
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/longest-palindromic-substring/solutions/255195/zui-chang-hui-wen-zi-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。