一个串可以含有许多镜像子串。我们的目标是求一个串的最大镜像子串(最长的镜像子串),如果有多个最大镜像子串,对称中心靠左的优先选中。例如:“abcdeefghhgfeiieje444k444lmn”的最大镜像子串是:“efghhgfe”
public class Test提取子串 {
public static void main(String[] args) {
System.out.println(getMaxMirrorString("abcdeefghhgfeiieje444k444lmn"));
}
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))
break; // 填空2
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;
}
}
原文地址:http://blog.csdn.net/tracysilocean/article/details/25971673