Leetcode#5 Longest Palindromic Substring

来源:互联网 发布:淘宝订单接口 编辑:程序博客网 时间:2024/06/17 13:47

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.

Difficulty: Medium

动态规划,a[i]][j]是否回文,通过a[i-1][j+1]来判断,也许从中间开始的话耗时会更少。

下面这个程序的复杂度应该是O(N2)。

string longestPalindrome(string s) {    int len = s.length();    if(len==1)        return s;     int a[len][len];     memset(a,0,sizeof(a));     int max1 = 0;     string b;     for(int i=1;i<s.length();i++)     {         for(int j=0; j<i;j++)         {             if(s[i]==s[j])                a[i][j] = a[i-1][j+1];            else                a[i][j]=1;            if(a[i][j]==0&&(i-j)>=max1)            {                b = s.substr(j,i-j+1);                max1 = i-j;            }         }     }     return b;    }


0 0
原创粉丝点击