获取一段字符串中最长的对称子串的长度

获取一段字符串中最长的对称子串,例如:sl1 232 1akfj12345678abcdcba87654321dssdf中最长的对称子串为:12345678abcdcba87654321

public class Main {

    public static void main(String[] args) {
        String regex = "(.)(.)(.?)(.?)(.?)(.?)(.?)(.?)(.?).?\\9\\8\\7\\6\\5\\4\\3\\2\\1"; //可以匹配最长为19的对称子串
        String str = "sl1 232 1akfj12345678abcdcba87654321dssdf";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        TreeMap map = new TreeMap();
        ArrayList list = new ArrayList();
        while(m.find()){
            map.put(m.group().length(), m.group());
        }
        int length = map.lastKey(); 
        if(length == 19){
            for(int i = str.indexOf(map.get(length))-1,j = i + map.get(length).length()+1; i >= 0 && j < str.length(); i--,j++ ){
                if(str.charAt(i) == str.charAt(j)){
                    System.out.println(str.charAt(i));
                    length += 2;
                }
            }
        }
        System.out.println(length);
    }

}

你可能感兴趣的:(Java学习笔记)