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"
这一题我是选择用动态规划来做,其中设f[i][j]为状态,则状态转移方程为:
true , i=j
f[i][j] = string[i] = string[j] , j = i + 1
string[i] = string[j] && f[i+1][j-1]
显然时间复杂度为O(n^2)
Code:(LeetCode运行96ms)
class Solution {
public:
string longestPalindrome(string s) {
const int n = s.size();
bool f[n][n];
//初始化
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
f[i][j] = false;
}
}
int max_length = 1, start = 0;
for (int i = 0; i < n; i++) {
f[i][i] = true;
for (int j = 0; j < i; j++) {
f[j][i] = (s[j] == s[i] && (i - j < 2 || f[j + 1][i - 1]));
if (f[j][i] && max_length < (i - j + 1)) {
max_length = i - j + 1;
start = j;
}
}
}
return s.substr(start, max_length);
}
};