LeetCode(5) Longest Palindromic Substring

题目为:

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.

使用动态规划,可以将时间复杂度降低到0(n^2)。

动态规划方程式为:

设dp[i][j]=true,表示从i到j的子串是回文子串。

则dp[i][j] = dp[i+1][j-1]   if s[i]=s[j] 

    dp[i][j] = false     if s[i]!=s[j]

代码如下:

public class Solution {
	public String longestPalindrome(String s) {
		int maxlength = 0;
		int head =0;
		if(s==null){
			return null;
		}
		if(s.length()==0){
			return null;
		}
		
		int n = s.length();
		boolean [][]dp = new boolean [n+1][n+1];
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				dp[i][j]=false;
			}
			dp[i][i]=true;
		}
		maxlength = 1;
		head = 0;
		for(int i=0;i<n-1;i++){
			if(s.charAt(i)==s.charAt(i+1)){
				dp[i][i+1] = true;
				if(maxlength<2&&dp[i][i+1]){
					maxlength = 2;
					head = i;
				}
				
			}
		}
		for(int length = 3; length <= n; length ++){
			
			for(int i=0;i+length-1<n;i++){
				if(s.charAt(i)==s.charAt(i+length-1)){
					dp[i][i+length-1] = dp[i+1][i+length-2];
					if(length>maxlength&&dp[i][i+length-1]){
						maxlength = length;
						head = i;
					}
				}
			}
		}
		return s.substring(head,head+maxlength);
    }
}






你可能感兴趣的:(LeetCode(5) Longest Palindromic Substring)