/*
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
*/
首先想到的是动态规划,单看到字符串长度差不多1000,遂放弃使用,看了大佬的解题思路回文子串问题,才发现还有另外一种思路,在写一个函数用来判断奇偶回文问题
子串长度为奇数:"aba"判断两边即可,中心点在b
子串长度为偶数:"abba"判断两边即可,中心点在两个字母bb之间
static int x = []() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(0);
return 0;
}();
class Solution {
public:
int exporta(string s, int L, int R){
while(L >= 0 && R < s.size() && s.at(L) == s.at(R)){
L--;
R++;
}
return R-L-1;
}
public:
string longestPalindrome(string s) {
if(s.length() < 1){
return "";
}
int start = 0, end = 0;
for(int i = 0; i < s.size(); i++){
int len1 = exporta(s, i, i);
int len2 = exporta(s, i, i+1);
int len = max(len1, len2);
if(len > end-start){
start = i - (len-1)/2;
end = i + len/2;
}
}
return s.substr(start, end-start+1);
//此处需注意substr的参数是返回从index开始的长度为num的字符串
}
};