背景:
所謂對稱子字符串,就是這個子字符串要麼是以其中一個詞對稱:比如 “aba”, “abcba”;要麼就完全對稱:比如"abba", "abccba"。
問題:
給你一個字符串,找出該字符串中對稱的子字符串的最大長度。
思路:
首先,我們用字符數組 char[] array 來保持這個字符串,假設現在已經遍歷到第 i 個字符,要找出以該字符爲“中心”的最長對稱字符串,我們需要用另兩個指針分別向前和向後移動,直到指針到達字符串兩端或者兩個指針所指的字符不相等。因爲對稱子字符串有兩種情況,所以需要寫出兩種情況下的代碼:
1. 第 i 個字符是該對稱字符串的真正的中心,也就是說該對稱字符串以第 i 個字符對稱, 比如: “aba”。代碼裏用 index 來代表 i.
public static int MaxLength1(char[] array ,int index){
int length=1;
int dif=1;//與index的距離
//下面的判斷順序若array[index-dif]==array[index+dif]在前將會拋出異常,
while((index-dif)>=0 &&(index+dif)<array.length &&array[index-dif]==array[index+dif]){
length+=2;
dif++;
}
return length;
}
2. 第 i 個字符串是對稱字符串的其中一箇中心。比如“abba”、
public static int MaxLength2(char []array ,int index){
int length=0;
int dif=0;//與index的距離
//下面的判斷順序若array[index-dif]==array[index+dif+1]在前將會拋出異常,
while((index-dif)>=0 &&(index+dif+1)<array.length &&array[index-dif]==array[index+dif+1]){
length+=2;
dif++;
}
return length;
}
有了這樣兩個函數,我們只需要遍歷字符串裏所有的字符,就可以找出最大長度的對稱子字符串了。
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("請輸入字符串!");
char[] n;
String a=sc.next();
n=a.toCharArray();//string類型轉char
int Maxlength=0;
for(int i=0;i<n.length;i++){
int tempLength=0;
int length1=MaxLength1(n,i);
int length2=MaxLength2(n,i);
tempLength=(length1>length2)?length1:length2;
if (tempLength > Maxlength) {
Maxlength = tempLength;
}
}
System.out.print(Maxlength);
}
因爲找出以第 i 個字符爲“中心”對稱字符串複雜度爲 O(N),所以整個算法的複雜度爲O(N^2)。
轉自:http://blog.csdn.net/beiyetengqing/article/details/7769221