Leecode 5
最长回文串
方法一:动态规划法,
对于一个子串而言,如果它是回文串,并且长度大于 22,那么将它首尾的两个字母去除之后,它仍然是个回文串。例如对于字符串 "ababa’’ 如果我们已经知道 `bab’'是回文串,那么ababa一定是回文串,这是因为它的首尾两个字母都是 “a”。边界条件就是i=j的时候,肯定是回文串,如果为2,当两个字符相同时候也为回文串。
代码
std::string Leecode5_longestPalindrome(std::string s) {
int n = s.size();
std::vector<std::vector<int>> dp(n, std::vector<int>(n));
std::string ans;
for (int l = 0; l < n; ++l) {
for (int i = 0; i + l < n; ++i) {
int j = i + l;
if (l == 0)
dp[i][j] = 1;
else if (l == 1)
dp[i][j] = (s[i] == s[j]);
else
dp[i][j] = (s[i] == s[j] && dp[i + 1][j - 1]);
if (dp[i][j] && l + 1 > ans.size()) {
ans = s.substr(i, l + 1);
}
}
return ans;
}