回文字符串就是正反字符串一样。
- public class Main19 {
- public static void main(String[] args) {
- System.out.println(getPalindrome("12ABCBA23"));
- }
- /**
- * 双指针法获取test最长回文子串
- * @param test
- * @return
- */
- public static String getPalindrome(String test){
- int length = test.length();
- /**
- * 第1个指针从字符串尾部开始
- * 第2个指针从字符串头部开始
- */
- 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));
- }
- }
- /**
- * 双指针法获取test最长回文子串
- * @param test 待测试的字符串
- * @return 回文字符串,没有返回空
- */
- public static String getMaxPalindromeChild(String test){
- if(null == test || test.length() == 0){
- return "";
- }
- int length = test.length();
- /**
- * 第1个指针从字符串尾部开始
- * 第2个指针从字符串头部开始
- */
- 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 "";
- }
- /**
- * 判断test指定范围的子串是否是回文
- * @param test 待测试的子串
- * @param leftPoint 左指针
- * @param rightPoint 右指针
- * @return true为回文,false不是
- */
- public static boolean isPalindrome(String test,int leftPoint ,int rightPoint){
- while (leftPoint < rightPoint && test.charAt(leftPoint) == test.charAt(rightPoint)){
- leftPoint++;
- rightPoint--;
- }
- return leftPoint >= rightPoint;
- }
- }