回文字符串就是正反字符串一样。
- public class Main19 {
- public static void main(String[] args) {
- System.out.println(getPalindrome("12ABCBA23"));
- }
- public static String getPalindrome(String test){
- int length = test.length();
- for(int point01 = length;point01 >= 1;point01--){
- for(int point02 = 0;point02 + point01 <= length;point02++){
- int left = point02;
- int right = point02 + point01 -1;
- while (left < right && test.charAt(left) == test.charAt(right)){
- left++;
- right--;
- }
- if(left >= right){
- return test.substring(point02,point01+1);
- }
- }
- }
- return "";
- }
- }
优化后:命名、方法行数、功能细化、抽取
- import java.nio.charset.StandardCharsets;
- import java.util.Scanner;
- public class Main19Optimize {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());
- while (scanner.hasNextLine()){
- String test = scanner.nextLine();
- // 输入12ABCBA23输出2ABCBA2
- System.out.println(getMaxPalindromeChild(test));
- }
- }
- public static String getMaxPalindromeChild(String test){
- if(null == test || test.length() == 0){
- return "";
- }
- int length = test.length();
- for(int rightPoint = length;rightPoint >= 1;rightPoint--){
- for(int leftPoint = 0;leftPoint + rightPoint <= length;leftPoint++){
- if(isPalindrome(test,leftPoint,leftPoint + rightPoint -1)){
- return test.substring(leftPoint,leftPoint +rightPoint);
- }
- }
- }
- return "";
- }
- public static boolean isPalindrome(String test,int leftPoint ,int rightPoint){
- while (leftPoint < rightPoint && test.charAt(leftPoint) == test.charAt(rightPoint)){
- leftPoint++;
- rightPoint--;
- }
- return leftPoint >= rightPoint;
- }
- }



