5. Longest Palindromic Substring

来源:互联网 发布:简单pdf解密软件 编辑:程序博客网 时间:2024/06/02 06:12

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);    }};




原创粉丝点击