5. Longest Palindromic Substring
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"
感觉自己好坑啊。。自己逻辑有问题需要训练吧!
class Solution {
public:
string longestPalindrome(string s) {
if(s.length()==0||s.length()==1) return s;
int max=0,maxid;
for(int i=0;i<s.length();i++)
{
int count=1,count2=0;
for(int l=1;l<=i&&i+l<s.length();l++){
if(s[i+l]==s[i-l]){
count+=2;
if(count>max){
max=count;
maxid=i-l;
}
}else break;
}
for(int l=0;l<=i&&i+l+1<s.length();l++){
if(s[i+l+1]==s[i-l]){
count2+=2;
if(count2>max){
max=count2;
maxid=i-l;
}
}else break;
}
}
if(max==0) return s.substr(0,1);
return s.substr(maxid,max);
}
};
榜首咋写的!
class Solution {
public:
string longestPalindrome(string s) {
string manaStr = "$#";
for (int i=0;i<s.size();i++) //首先构造出新的字符串
{
manaStr += s[i];
manaStr += '#';
}
vector<int> rd(manaStr.size(), 0);//用一个辅助数组来记录最大的回文串长度,注意这里记录的是新串的长度,原串的长度要减去1
int pos = 0, mx = 0;
int start = 0, maxLen = 0;
for (int i = 1; i < manaStr.size(); i++)
{
rd[i] = i < mx ? min(rd[2 * pos - i], mx - i) : 1;
while (i+rd[i]<manaStr.size() && i-rd[i]>0 && manaStr[i + rd[i]] == manaStr[i - rd[i]])//这里要注意数组越界的判断,源代码没有注意,release下没有报错
rd[i]++;
if (i + rd[i] > mx) //如果新计算的最右侧端点大于mx,则更新pos和mx
{
pos = i;
mx = i + rd[i];
}
if (rd[i] - 1 > maxLen)
{
start = (i - rd[i]) / 2;
maxLen = rd[i] - 1;
}
}
return s.substr(start, maxLen);
}
};
又是一种厉害的解法
class Solution {
public:
string longestPalindrome(string s) {
int begin = 0, longest = 0, len = 0, bias = 0;
for (int i=0; i<s.size(); ++i) {
// 当前字符和前一个字符相同则跳过
if (i > 0 && s[i] == s[i-1]) continue;
bias = 0;
// 从当前字符开始,向后找到和当前字符相同的字符,作为回文串的中心
for (int j=i; j<s.size()-1; ++j)
if (s[j] == s[j+1]) ++bias;
else break;
// 第i轮循环可能找到的最长回文子串若不大于此前的最大值,则结束循环
if ((s.size() - i)*2 - bias - 1 <= longest) break;
// 从回文串的中心向两侧寻找
for (len=1; len<i+1 && len<s.size()-i-bias; ++len) {
if (s[i-len] != s[i+len+bias])
break;
}
// 计算当前最长回文子串的长度以及起始位置
if (longest < len*2 - 1 + bias) {
longest = len*2 - 1 + bias;
begin = i - len + 1;
}
}
return s.substr(begin, longest);
}
};
作者:saul-9
链接:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/yun-xing-shi-jian-0msji-bai-100de-da-an-by-saul-9/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。