笔试题-最长回文子串

题目描述

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:

输入: “babad”
输出: “bab”
注意: “aba” 也是一个有效答案。
示例 2:

输入: “cbbd”
输出: “bb”

代码



import java.util.*;

public class MyTest07 {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    String s1 = longestPalindrome(s);
    System.out.println(s1);

}

    public static String longestPalindrome(String s) {
        Map<Integer,String> map=new HashMap<>();
        
        for (int i = 0; i < s.length()-1; i++) {
            for (int j = s.length()-1; j >i; j--) {
                String str=s.substring(i,j+1);
                if (isAllSame(str)){
                    map.put(str.length(),str);

                }
            }

        }
        Set<Integer> integers = map.keySet();
        Integer max = Collections.max(integers);
        String s1 = map.get(max);
        return s1;


    }

    private static boolean isAllSame(String string){

        for (int i = 0; i<(string.length()/2) ; i++) {
            if (string.charAt(i)!=string.charAt(string.length()-i-1)){
                return false;
            }
        }
        return true;

    }


}



发布了84 篇原创文章 · 获赞 15 · 访问量 9986

猜你喜欢

转载自blog.csdn.net/yalu_123456/article/details/102672399