对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。
输入格式:
 输入在一行中给出长度不超过1000的非空字符串。
输出格式:
 在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
思路:
回文子串为对称字符,所以我们从中间先两边时遍历左端=右端
- 我们需要从头遍历 将当前的i值作为中间值从i开始像两边遍历判断左端是否等于右端 并且我们需要得出回文字符串的长度(因此我们可以得出需要用双重循环进行遍历 判断 i表示当前字符的中间值,j表示从i向两边遍历)
- 当回文串为奇数时
for (int j = 0; i - j >= 0 && i + j < len; j++) {
                if (ch[i - j] != ch[i + j]) {
                    break;
                }
                if (res < 2 * j + 1) {
                    res = 2 * j + 1;
                }
            }
- 当回文子串为偶数时
for (int j = 0; i - j >= 0 && i + j + 1 < len; j++) {
                if (ch[i - j] != ch[i + j + 1]) {
                    break;
                }
                if (res < 2 * j + 2) {
                    res = 2 * j + 2;
                }
            }
注意
当回文串为偶数是
回文串:1  2  2  1
当前i     i
所以我们下一次比较的对象时
回文串:1      2      2      1
      i-j                  i+j+1
所以回文子串的长度为  2*j+2
源码
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        char[] ch = str.toCharArray();
        int res = 0;
        int len = str.length();
        for (int i = 0; i < len; i++) {
            for (int j = 0; i - j >= 0 && i + j < len; j++) {
                if (ch[i - j] != ch[i + j]) {
                    break;
                }
                if (res < 2 * j + 1) {
                    res = 2 * j + 1;
                }
            }
            for (int j = 0; i - j >= 0 && i + j + 1 < len; j++) {
                if (ch[i - j] != ch[i + j + 1]) {
                    break;
                }
                if (res < 2 * j + 2) {
                    res = 2 * j + 2;
                }
            }
        }
        System.out.println(res);
    }
}










