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”
翻譯
給定一個字符串 s,找到 s 中最長的迴文子串。你可以假設 s 的最大長度爲1000。
示例 1:
輸入: “babad”
輸出: “bab”
注意: "aba"也是一個有效答案。
示例 2:
輸入: “cbbd”
輸出: “bb”
分析
對每一個字符和每兩個字符中間的間隔作爲對稱軸向兩邊延展,找到最長迴文子串。複雜度爲O(n^2)。有O(n)的算法,暫時沒看明白。
c++實現
class Solution {
public:
string expend(string s,int left,int right) {
while (left >= 0 && right < s.length())
{
if (s[left] == s[right])
{
left--;
right++;
}
else
break;
}
return s.substr(left+1,right-left-1);
}
string longestPalindrome(string s) {
string R = "";
for (int i = 0; i < s.length()-1; i++)
{
string p1 = expend(s,i,i);
if (p1.length() > R.length())
R = p1;
string p2 = expend(s,i,i+1);
if (p2.length() > R.length())
R = p2;
}
if (R.length() < 1)
return s.substr(s.length()-1,1);
return R;
}
};