LeetCode--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.

题目:查找字符串中最长回文子串。

思路:使用动态规划

注意:DP数组定义为boolen类型,不要定义为int类型。不然会报超时错误!!!boolen(18ms) int(28ms)  

boolen类型的数据操作比int类型的数据操作时间短吗??????

To improve over the brute force solution, we first observe how we can avoid unnecessary re-computation while validating palindromes. Consider the case ''ababa''''ababa''. If we already knew that ''bab''''bab'' is a palindrome, it is obvious that ''ababa''''ababa'' must be a palindrome since the two left and right end letters are the same.

We define P(i,j)P(i,j) as following:

P(i,j)={true,if the substring SiSj is a palindromefalse,otherwise. P(i,j)={true,if the substring Si…Sj is a palindromefalse,otherwise. 

Therefore,

P(i, j) = ( P(i+1, j-1) \text{ and } S_i == S_j )P(i,j)=(P(i+1,j1) and Si==Sj)

The base cases are:

P(i, i) = trueP(i,i)=true

P(i, i+1) = ( S_i == S_{i+1} )P(i,i+1)=(Si==Si+1)

This yields a straight forward DP solution, which we first initialize the one and two letters palindromes, and work our way up finding all three letters palindromes, and so on...

Complexity Analysis

  • Time complexity : O(n^2)O(n2). This gives us a runtime complexity of O(n^2)O(n2).

  • Space complexity : O(n^2)O(n2). It uses O(n^2)O(n2) space to store the table.

public static String longestPalindrome(String s) {
		if(s==null)
			return null;
		if(s.length()<=1)
			return s;
		String longString=null;
		boolean [][]dp=new boolean[s.length()][s.length()];
		int maxlength=0;
		int start=0;
		int end=0;
		dp[0][0]=true;
		for(int i=1;i<s.length();i++){
			dp[i][i]=true;
			dp[i][i-1]=true;
		}
		for(int k=2;k<=s.length();k++){
			for(int j=0;j<=s.length()-k;j++){
				int l=j+k-1;
				if(s.charAt(j)==s.charAt(l)&&dp[j+1][l-1]){
					dp[j][l]=true;
					if(k>maxlength)
					{
						start=j;
						end=l+1;
						maxlength=k;
					}
				}
			}
		}
		longString=s.substring(start, end);
        return longString;
    }


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