输入一串字符串,获取其中最长的镜像字符串
例如
cabecbad
对与子串:abecba 除去c 剩下 abeba即为最长的镜像字符串 长度为5
算法思想:
对于每一个字符,都可以选择加入子串或者舍弃 然后判断是否是镜像字符串
package myWork;
import java.util.ArrayList;
import java.util.List;
public class Mirror {
private static int len = 0;
public static void main(String args[]) {
List<Character> chars = new ArrayList<>();
String s = "cabecbad";
mirror(s, 0, chars);
System.out.println(len);
}
public static void mirror(String s, int index, List<Character> chars) {
// 已取完字符
if (index >= s.length()) {
// 判断是否是镜像
for (int i = 0; i < chars.size() / 2; i++) {
if (chars.get(i) != chars.get(chars.size() - i - 1)) {
return;
}
}
if (chars.size() > len) {
len = chars.size();
return;
}
} else if (s.length() - index + chars.size() < len) {
//剪支
return;
} else {
List<Character> charsCopyone = new ArrayList<>();
charsCopyone.addAll(chars);
mirror(s, index + 1, charsCopyone);
List<Character> charsCopytwo = new ArrayList<>();
charsCopytwo.addAll(chars);
charsCopytwo.add(s.charAt(index));
mirror(s, index + 1, charsCopytwo);
}
}
}