LeetCode-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:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
思路:首先要理解回文字符串是什么,就一个字符来说,如“a”本身就是回文字符串,两个字符“aa”也是回文字符串,可以发现S[i]==S[j],其他的回文字符串可以在单词或双字符回文字符串上进行扩展,条件是S[i-1]==S[j+1].下面提供两种解法,解法一遍历字符串的进行单、双字符串的扩展,而解法二则更为优化,若出现“aa”这种情况,则直接找出右端点right为第二个“a”,再进行双向扩展。
解法一:
class Solution
{
public:
string longestPalindrome(string s)
{
int len = s.size();
int start = 0, last = 0;
if (len == 0)return s;
for (int i = 0; i < len - 1; ++i)
{
expandAroundCenter(s, i, i, start, last);
expandAroundCenter(s, i, i+1, start, last);
}
return s.substr(start, last - start + 1);
}
private:
void expandAroundCenter(const string& s, int b, int e, int &start, int &last)
{
int len = s.size();
while (b >= 0 && e < len&&s[b] == s[e])
{
b--,++e;
}
++b,--e;
if (e - b > last - start)
{
start = b;
last = e;
}
}
};
解法二:
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size(), len = 0, start = 0;
for (int i = 0; i < n; i++) {
int left = i, right = i;
while (right < n && s[right + 1] == s[right]) right++;
i = right;
while (left > 0 && right < n - 1 && s[left - 1] == s[right + 1]) {
left--;
right++;
}
if (len < right - left + 1) {
len = right - left + 1;
start = left;
}
}
return s.substr(start, len);
}
};