Longest Palindromic Substring

来源:互联网 发布:三菱plc编程入门 编辑:程序博客网 时间:2024/05/01 15:02

I: 二维DP

外层循环是子串长度,内层循环是子串起始位置,同时更新最长的长度和起始位置,用于返回时调用substr

class Solution {public:    string longestPalindrome(string s) {        if (s.size()==0) return NULL;        int len=1, start=0;        int n=s.size();        bool t[n][n];        for (int i=0; i<n; i++) {            t[i][i] = true;        }        for (int l=2; l<=n; l++) // outer loop for substring length        {            for (int i=0; i<=n-l; i++) { // inner loop for the start of the substring                int j=i+l-1;                t[i][j]=false;                if ((j-i>1 && t[i+1][j-1] && s[i]==s[j]) || (j-i==1 && s[i]==s[j])) {                    t[i][j]=true;                    if (l>len) {                        len=l;                        start=i;                    }                }            }        }        return s.substr(start,len);    }};


0 0
原创粉丝点击