leetcode Longest Palindromic Substring

 

import jdk.nashorn.internal.ir.GetSplitState;

import java.io.*;
import java.util.*;

public class longestPalindromicSubstring {
public static String longestPalindrome(String s) {
if(s.length() == 1 )
return s.substring(0,1);
else{
int[][] dp = new int[s.length() + 5][s.length() + 5];
for (int i=0;i< s.length();i++)
for(int j=i+1;j<s.length();j++){
dp[i][j] = -1;
}
for (int i=0;i<s.length();i++)
dp[i][i] = 1;
int left = 0, right = 0, Max = 1;
for (int l= 2 ; l<=s.length() ; l++)
for(int i = 0; i< s.length() ; i++){
int j = i +l -1 ;
if(j >= s.length()) break;
if( s.charAt(i)== s.charAt(j) && l == 2){
dp[i][j] = 2 ;
if(dp[i][j] >= Max ){
Max = dp[i][j];
left = i;
right = j;
}
}
else if(s.charAt(i)== s.charAt(j) && l>=3 &&dp[i+1][j-1]!=-1){
dp[i][j] = dp[i+1][j-1] + 2 ;
if(dp[i][j] >= Max ){
Max = dp[i][j];
left = i;
right = j;
}
}

}
/* System.out.print("left: ");
System.out.println(left);
System.out.print("right: ");
System.out.println(right);
System.out.println(s.substring(left, right+1));*/
return s.substring(left, right+1) ;
}
}

public static void main(String args[]) throws Exception{
// System.out.print("jiaweitao");
// MyIO.ScannerTest();
while(true){
Scanner sca = new Scanner(System.in);
String str = sca.nextLine();
//System.out.println(str.substring(0,str.length()+1));
//System.out.println(str.substring(1,str.length()-1));
// System.out.println(longestPalindrome(str.substring(1,str.length()-1)));
// System.out.println(longestPalindrome(str));
longestPalindrome(str);

}
}
}

posted on 2018-07-19 21:03  爱装逼的书呆子  阅读(77)  评论(0编辑  收藏  举报

导航