串“abcba”以字母“c”爲中心左右對稱;串“abba” 是另一種模式的左右對稱。這兩種情況我們都稱這個串是鏡像串。特別地,只含有1個字母的串,可以看成是第一種模式的鏡像串。
一個串可以含有許多鏡像子串。我們的目標是求一個串的最大鏡像子串(最長的鏡像子串),如果有多個最大鏡像子串,對稱中心靠左的優先選中。例如:“abcdeefghhgfeiieje444k444lmn”的最大鏡像子串是:“efghhgfe”
下面的靜態方法實現了該功能,請仔細閱讀並分析代碼,填寫空白處的代碼,使得程序的邏輯合理,結果正確。
// 求最大(長度最大)鏡像對稱子串
public static String getMaxMirrorString(String s) {
String max_s = ""; // 所求的最大對稱子串
for (int i = 0; i < s.length(); i++) {
// 第一種對稱模式
int step = 1;
try {
for (;;) {
if (s.charAt(i - step) != s.charAt(i + step))
break;
step++;
}
} catch (Exception e) {
}
String s1 = s.substring(i-step+1,i+step); // 填空1
// 第二種對稱模式
step = 0;
try {
for (;;) {
if (s.charAt(i - step) != s.charAt(i + step+1))// 填空2
break;
step++;
}
} catch (Exception e) {
}
String s2 = s.substring(i-step+1,i+step+1 );
if (s1.length() > max_s.length())
max_s = s1;
if (s2.length() > max_s.length())
max_s = s2;
}
return max_s;
}