Description:
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"
Solution:
class Solution {
public:
string str_helper(string s, int left, int right)
{
int n = s.length();
while(left>=0 && right<=n-1 && s[left]==s[right]){
left--;
right++;
}
return s.substr(left+1, right-left-1);
}
string longestPalindrome(string s) {
if(s.length() <= 1)
return s;
string longest = s.substr(0,1);
for (int i=0; i<s.length(); i++){
string tmp = str_helper(s, i, i);
if (tmp.length() > longest.length()) {
longest = tmp;
}
tmp = str_helper(s, i, i+1);
if (tmp.length() > longest.length()) {
longest = tmp;
}
}
return longest;
}
};
本文介绍了一种高效算法来找出给定字符串中的最长回文子串。通过使用中心扩展法,该算法能够处理不同长度的回文串,并提供了一个C++实现示例。
604

被折叠的 条评论
为什么被折叠?



