005. Longest Palindromic Substring
Difficulty: Medium
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
思路
回文可分为两种情况:AA’和AbA’(A为字符串,A’为A的反转字符串,b为一个字符)。
对于字符串s的每个字符,分别计算把它当作A的末尾字符和b时可取得的最长回文。
使用string的substr方法获取该回文子串。
代码
[C++]
class Solution {
public:
string longestPalindrome(string s) {
if(s.length() <= 1) return s;
string res;
for (int i = 0; i < s.length(); ++i) {
string s1, s2;
s1 = longestPalindromeCore(s, i, i + 1);
s2 = longestPalindromeCore(s, i , i);
if (res.length() < s1.length())
res = s1;
if (res.length() < s2.length())
res = s2;
if(res.length() == s.length())
break;
}
return res;
}
string longestPalindromeCore(string &s, int begin, int end) {
while (begin >= 0 && end < s.length()) {
if(s[begin] != s[end])
break;
begin--;
end++;
}
return s.substr(begin + 1, end - 1 - begin);
}
};