Longest Palindromic Substring

来源:互联网 发布:mac中的照片在哪里 编辑:程序博客网 时间:2024/05/22 16:54

题目:
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
动态规划
动态规划都要有:1)一个标志位flag;2)双层循环;3)判断是否最优,如max等;
代码:

class Solution {public:    string longestPalindrome(string s) {        int len=s.size();        bool flag[len][len];        int sstart=0;        int send=0;        int max=1;        for(int i=0;i<len;i++)        {             for(int j=0;j<len;j++)             {                if(i>=j) flag[i][j]=true;                 else flag[i][j]=false;             }        }        for(int j=1;j<len;j++)        {            for(int i=0;i<j;i++)            {                if(s[i]==s[j])                {                    flag[i][j]=flag[i+1][j-1];                    if(flag[i][j]==true && j-i+1>max)                     {                        max=j-i+1;                        sstart=i;                        send=j;                    }                }                else flag[i][j]=false;            }        }        string result=s.substr(sstart,max);        return result;    }};
0 0
原创粉丝点击