题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param A string字符串 * @return int整型 */ int getLongestPalindrome(string A) { // write code here int n = A.size(); vector<vector<bool>> dp(n, vector<bool>(n, false)); int start = 0, maxLength = 1; for(int i = 0; i < n; ++i) { dp[i][i] = true; } for(int i = 0; i < n - 1; ++i) { if(A[i] == A[i + 1]) { start = i; maxLength = 2; dp[i][i + 1] = true; } } for(int len = 3; len <= n; ++len) { for(int i = 0; i <= n - len; ++i) { int j = i + len - 1; if(A[i] == A[j] && dp[i + 1][j - 1]) { dp[i][j] = true; maxLength = len; start = i; } } } return maxLength; } };
先考虑单个字符,然后考虑长度为2 的回文字符,最后考虑其他情况