码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Longest Palindromic Substring

时间:2016-05-12 22:22:17      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

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,j?1) and S?i??==S?j??)

The base cases are:

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

P(i, i+1) = ( S_i == S_{i+1} )P(i,i+1)=(S?i??==S?i+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(n?2??). This gives us a runtime complexity of O(n^2)O(n?2??).

  • Space complexity : O(n^2)O(n?2??). It uses O(n^2)O(n?2??) 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

标签:

原文地址:http://blog.csdn.net/zlele0326/article/details/51356456

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!