算法分析与设计丨第十五周丨LeetCode(19)——Longest Palindromic Substring(Medium)

来源:互联网 发布:简单菜谱软件下载 编辑:程序博客网 时间:2024/06/06 12:46

题目描述:

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"

题目解析:

动态规划。题目做得有点丑陋。核心思想是先看长度为1和2的回文串,然后从长度为3到size - 1遍历,如果发现减去头和尾的字串是回文并且头和尾的字母相等,则将其加入回文串中。



class Solution {public:    string longestPalindrome(string s) {        int size = s.size();                vector<vector<int> > dp(size,vector<int>(size,0));                int max_left = 0,max_right = 0;        string max_substr = "";                for(int i = 0;i < size;++i)        {            dp[i][i] = 1;            if(i != size - 1 && s[i] == s[i + 1])            {                dp[i][i + 1] = 1;                //the length of 2 is Palindromic                 max_left = i;                max_right = i + 1;            }                        }                                for(int strlen = 3; strlen <= size;++strlen)        {                        for(int i = 0;i <= size - strlen;++i)            {                int j = i + strlen - 1;                if(dp[i + 1][j - 1] == 1 && s[i] == s[j])                {                    dp[i][j] = 1;                    string temp = s.substr(i,strlen);                    if(temp.size() > max_right - max_left + 1)                    {                                                max_left = i;                        max_right = j;                        max_substr = temp;                    }                                    }                                }        }                bool flag = false;        if(max_left == 0 && max_right == 0 || max_right - max_left == 1)        {            for(int i = 0;i < size - 1;++i)            {                if(dp[i][i + 1] == 1)                {                    max_substr = s.substr(i,2);                    flag = true;                    break;                }            }        }                if(max_left == 0 && max_right == 0 && flag == false)            return s.substr(0,1);                               return max_substr;            }};



阅读全文
0 0
原创粉丝点击