Leetcode118: Longest Palindromic Substring

本文介绍了一种利用动态规划解决寻找字符串中最长回文子串问题的方法,将时间复杂度降低至O(N²),并提供了详细的算法实现步骤及代码示例。

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.

使用动态规划,这样可以把时间复杂度降到O(N²),空间复杂度也为O(N²)。做法如下:

首先,写出动态转移方程。

Define P[ i, j ] ← true iff the substring Si … Sj is a palindrome, otherwise false.

P[ i, j ] ← ( P[ i+1, j-1 ] and Si = Sj ) ,显然,如果一个子串是回文串,并且如果从它的左右两侧分别向外扩展的一位也相等,那么这个子串就可以从左右两侧分别向外扩展一位。

其中的base case是

P[ i, i ] ← true
P[ i, i+1 ] ← ( Si = Si+1 )

然后,看一个例子。

假设有个字符串是adade,现在要找到其中的最长回文子串。使用上面的动态转移方程,有如下的过程:


按照红箭头->黄箭头->蓝箭头->绿箭头->橙箭头的顺序依次填入矩阵,通过这个矩阵记录从i到j是否是一个回文串。

class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.length();  
        int longestBegin = 0;  
        int maxLen = 1;  
        bool table[1000][1000] = {false};  
        for (int i = 0; i < n; i++) {  
            table[i][i] = true;  
        }  
        for (int i = 0; i < n-1; i++) {  
            if (s[i] == s[i+1]) {  
                table[i][i+1] = true;  
                longestBegin = i;  
                maxLen = 2;  
            }  
        }  
      for (int len = 3; len <= n; len++) {  
        for (int i = 0; i < n-len+1; i++) {  
          int j = i+len-1;  
          if (s[i] == s[j] && table[i+1][j-1]) {  
            table[i][j] = true;  
            longestBegin = i;  
            maxLen = len;  
          }  
        }  
      }  
      return s.substr(longestBegin, maxLen);  
    }
};

改进版:

class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.length();
        if(n<=1)    return s;
        int index1=0;
        int max=0;
        int c,j;
        
        for (int i = 0; i < n; ++i)
        {
        	for (j = 0; (i-j)>=0 && (i+j)<n; ++j)
        	{
        		if(s[i-j] != s[i+j])
        			break;
        		c = j*2+1;
        	}
        	
        	if(c>max)
        	{
        		max = c;
        		index1 = i-j+1;
        	}

        	for(j = 0; (i-j)>=0 && (i+j+1)<n; ++j)
        	{
        		if(s[i-j]!=s[i+j+1])
        			break;
        		c = j*2+2;
        	}
        	if (c>max)
        	{
        		max = c;
        		index1 = i-j+1;
        	}
        }
        return s.substr(index1, max);
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值