题目:
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.
//DP,f[i][j]表示从s[i]-s[j]表示的字符串是否是回文
class Solution {
public:
string longestPalindrome(string s) {
if (s.size() == 0)
return s;
bool f[1000][1000] = { false };
int len = 1;
int ss = 0;
//初始化
for (int i = 0; i < s.size(); i++)
f[i][i] = true;
for (int j = 1; j < s.size(); j++) {
for (int i = 0; i < j; i++) {
if (s[i] == s[j]) {
if (i + 1 == j)
f[i][j] = true;
else
f[i][j] = f[i + 1][j - 1];
if (f[i][j] && len < j - i + 1) {
len = j - i + 1;
ss = i;
}
}
else
f[i][j] = false;
}
}
return s.substr(ss, len);
}
};
本文介绍了一种使用动态规划方法来寻找给定字符串中最长回文子串的有效算法。该算法通过构建一个二维布尔数组来记录子串是否为回文,并通过迭代更新最长回文子串的位置和长度。
285

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



