LeetCode:Longest Palindromic Substring
问题描述
Given a string s, return the longest palindromic substring in s. 给一个数组s, 返回s中最长的回文子串
Example1
Input: s = “babad”
Output: “bab”
Explanation: “aba” is also a valid answer.
Example2
Input: s = “cbbd”
Output: “bb”
方法思路
采用的是遍历数组的方法,以字符串中的每一个字符为中心点,分别向左右两边延申并比较对应的值是否相同,因为存在 xyx 和 xx 两种中心点,所以对应每个中心点,都存在两种不同的起始情况。
代码如下(示例):
class Solution {
public String longestPalindrome(String s) {
//首先判断字符串是否为空
if(s == null || s.length() < 1) return "";
//设置start和end,它们分别对应最长回文子串的初始坐标和结束坐标
int start = 0;
int end = 0;
for(int i = 0; i < s.length(); i++){
//xyx的情况
int len1 = expandAroundCenter(s,i,i);
//xx的情况
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);
}
//设置方法进行以i为中心向左右拓展
private int expandAroundCenter(String s, int left, int right){
int L = left;
int R = right;
//s中L坐标的值和R坐标的值必须相等才能进行下一次循环
while( L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)){
R++;
L--;
}
//返回获取的回文子串的真实长度
return R-L-1;
}
}