对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
分析
1.只有 一个字符的时候,返回1.
2.abba
3.abcba
代码
import java.util.Scanner;public class LongSubStr {private static int getSum(char[] arr, int left, int right) {int sum = 0;while (arr[left]== arr[right]){sum +=2;left--;right++;if(left <0|| right > arr.length-1){break;}}return sum;}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);String str = scanner.nextLine();char[] arr = str.toCharArray();if(arr.length == 1){System.out.println(1);return;}int max = -1;for(int i = 0; i < arr.length; i++){if(i+1>arr.length-1){continue;}if(arr[i]!=arr[i+1])//abcba{int left = i - 1;int right = i + 1;if(left<0||right>arr.length-1){continue;}int sum = getSum(arr, left, right)+1;if(max<sum){max = sum;}}else//abba{int left = i;int right = i + 1;if(left<1||right>arr.length-1){continue;}int sum = getSum(arr, left, right);if(max<sum){max = sum;}}}System.out.println(max);}}