1. 程式人生 > >Leetcode005--字串中最大的迴文子串

Leetcode005--字串中最大的迴文子串

一、原題


  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. 

二、中文

給定一個字串S,找出它的最大的迴文子串,你可以假設字串的最大長度是1000,而且存在唯一的最長迴文子串 

三、舉例

如字串ekwr abcdcba asjflasj的最大非重複子串是abcdcba

四、思路


根據迴文的特性,一個大回文按比例縮小後的字串也必定是迴文,比如ABCCBA,那BCCB肯定也是迴文。我們可以先把所有長度最短為1的子字串計算出來,根據起始位置從左向右,這些必定是迴文。然後計算所有長度為2的子字串,再根據起始位置從左向右。到長度為3的時候,我們就可以利用上次的計算結果:如果中心對稱的短字串不是迴文,那長字串也不是,如果短字串是迴文,那就要看長字串兩頭是否一樣

五、程式


package LeetCode;

public class Leetcode005 {
	public static void main(String args[]){
		String str = "sdjfljsaaaddasfabcdcbaoqeiur";
		System.out.println(longestPalindrome(str));
	}
	
       
    public static String longestPalindrome(String s) {
    	int maxLength = 0;
    	int maxStart = 0;
    	int len = s.length();
    	
    	boolean[][] dp = new boolean[len][len];
    	
    	//i表示的是字串的長度
    	for(int i = 0; i < len; i++){
    		
    		//j表示的是字串的起始位置
    		for(int j = 0; j < len - i; j++){
    			//也就是字串中只有一次字元的時候
    			if(i==0 || i = 1){
    				dp[j][j] = true;
    			}else if(s.charAt(j+i)==s.charAt(j)){
    				//如果左右兩端相等,那隻要中心對稱子字串是迴文就是迴文
    				dp[j][j + i] = dp[j + 1][j + i - 1];
    			}else{
                    //否則不是迴文
                    dp[j][j+i] = false;
    			}
    			
                // 如果中心字串是迴文,也就是該字串是迴文的,就將該最大的長度加1
                if(dp[j][j+i] && i > maxLength){
                    maxLength = i + 1;
                    maxStart = j;
                }
    		}
    	}
    	return s.substring(maxStart,maxStart + maxLength);
    }
}

------------------------output-----------------------------

abcdcba