LeetCode - LongestPalinSubstr和longestPalinSubseq

class longestPalinSubstr{
	public static void main(String[] args){
		String s = "hahGeeks4";
		int l = new longestPalinSubstr().longestPalinSubstr(s);
		System.out.println(l);
	}
	
	public int longestPalinSubstr (String s){
		char[] str = s.toCharArray();
		int n = str.length;
		int[] S = new int[n]; //LPS ends at i;
		
		S[0]=1;
		S[1]=(str[0]==str[1])?2:1;
		
		for (int i = 2; i<n; i++){
			if (S[i-1]==i) S[i] = 1;
			else if (str[i]==str[i-S[i-1]-1]) S[i] = S[i-1]+2;
			else S[i]=1;
		}
		int max = 0 ;
		for (int i=0; i<S.length; i++){
			if (max<S[i]) max = S[i];
		}
		return max;
	}


}

 

//A Dynamic Programming based Python Program for the Egg Dropping Puzzle
class longestPalinSubseq
{
 
    // A utility function to get max of two integers
    static int max (int x, int y) { return (x > y)? x : y; }
      
    // Returns the length of the longest palindromic subsequence in seq
    static int lps(String seq)
    {
       int n = seq.length();
       int i, j, cl;
       int L[][] = new int[n][n];  // Create a table to store results of subproblems
      
       // Strings of length 1 are palindrome of lentgh 1
       for (i = 0; i < n; i++)
           L[i][i] = 1;
              
        // Build the table. Note that the lower diagonal values of table are
        // useless and not filled in the process. The values are filled in a
        // manner similar to Matrix Chain Multiplication DP solution (See
        // http://www.geeksforgeeks.org/archives/15553). cl is length of
        // substring
        for (cl=2; cl<=n; cl++)
        {
            for (i=0; i<n-cl+1; i++)
            {
                j = i+cl-1;
                if (seq.charAt(i) == seq.charAt(j) && cl == 2)
                   L[i][j] = 2;
                else if (seq.charAt(i) == seq.charAt(j))
                   L[i][j] = L[i+1][j-1] + 2;
                else
                   L[i][j] = max(L[i][j-1], L[i+1][j]);
            }
        }
              
        return L[0][n-1];
    }
          
    /* Driver program to test above functions */
    public static void main(String args[])
    {
        String seq = "GEEKSFORGEEKS";
        int n = seq.length();
        System.out.println("The lnegth of the lps is "+ lps(seq));
    }
}

 

转载于:https://my.oschina.net/vegechick/blog/1588837

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值