1. 程式人生 > >java-最長迴文串-中心擴充套件演算法

java-最長迴文串-中心擴充套件演算法

import java.util.*;

public class nk {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		String str = sc.next();
		System.out.println(getResult(str));
	}
	/**
	 * 以字元陣列中的某個字元為中心,向左右擴充套件,遇到迴文串則返回
	 * @param ch 要檢查的字串陣列
	 * @param start 左擴充套件
	 * @param end   右擴充套件
	 * @return      返回遇到最長迴文串
	 */
	public static String getEvery(char[] ch,int start,int end){
		int length = ch.length;
		while(start>=0 && end<=length-1 && ch[start] == ch[end]){
			start --;
			end ++;
		}
		return String.valueOf(ch).substring(start+1,end);//因為擷取區間是左閉又開
	}
	/**
	 * 返回某個字串中包含的最長迴文串,其中遍歷該字串,以字串中的每個字元為中心尋找最長迴文串,迴文串分為奇數型和偶數型
	 * @param str
	 * @return
	 */
	public static String getResult(String str){
		char[] ch = str.toCharArray();
		String result = "";
		String tmp = "";
		for(int i =0;i<ch.length;i++){
			tmp = getEvery(ch,i,i);//以每個字元為中心,且返回的是奇數型迴文串
			if(tmp.length()>result.length()){
				result = tmp;
			}
			tmp = getEvery(ch,i,i+1); //以每個字母為中心,且返回的是偶數型迴文串
			if(tmp.length()>result.length()){
				result = tmp;
			}
		}
		return result;	
	}
	
}