栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

最长回文子符串

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

最长回文子符串

回文字符串就是正反字符串一样。

  1. public class Main19 {  
  2.     public static void main(String[] args) {  
  3.         System.out.println(getPalindrome("12ABCBA23"));  
  4.     }  
  5.   
  6.       
  7.     public static String getPalindrome(String test){  
  8.         int length = test.length();  
  9.           
  10.         for(int point01 = length;point01 >= 1;point01--){  
  11.             for(int point02 = 0;point02 + point01 <= length;point02++){  
  12.                 int left = point02;  
  13.                 int right = point02 + point01 -1;  
  14.                 while (left < right && test.charAt(left) == test.charAt(right)){  
  15.                     left++;  
  16.                     right--;  
  17.                 }  
  18.                 if(left >= right){  
  19.                     return test.substring(point02,point01+1);  
  20.                 }  
  21.             }  
  22.   
  23.         }  
  24.         return "";  
  25.     }  
  26. } 

优化后:命名、方法行数、功能细化、抽取

  1. import java.nio.charset.StandardCharsets;  
  2. import java.util.Scanner;  
  3.   
  4.   
  5. public class Main19Optimize {  
  6.     public static void main(String[] args) {  
  7.         Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());  
  8.         while (scanner.hasNextLine()){  
  9.             String test = scanner.nextLine();  
  10.             // 输入12ABCBA23输出2ABCBA2  
  11.             System.out.println(getMaxPalindromeChild(test));  
  12.         }  
  13.     }  
  14.   
  15.       
  16.     public static String getMaxPalindromeChild(String test){  
  17.         if(null == test || test.length() == 0){  
  18.             return "";  
  19.         }  
  20.         int length = test.length();  
  21.           
  22.         for(int rightPoint = length;rightPoint >= 1;rightPoint--){  
  23.             for(int leftPoint = 0;leftPoint + rightPoint <= length;leftPoint++){  
  24.                if(isPalindrome(test,leftPoint,leftPoint + rightPoint -1)){  
  25.                    return test.substring(leftPoint,leftPoint +rightPoint);  
  26.                }  
  27.             }  
  28.         }  
  29.         return "";  
  30.     }  
  31.   
  32.       
  33.     public static boolean isPalindrome(String test,int leftPoint ,int rightPoint){  
  34.         while (leftPoint < rightPoint && test.charAt(leftPoint) == test.charAt(rightPoint)){  
  35.             leftPoint++;  
  36.             rightPoint--;  
  37.         }  
  38.         return  leftPoint >= rightPoint;  
  39.     }  
  40. }  

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/930879.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号