筆試題-最長迴文子串

題目描述

給定一個字符串 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;

    }


}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章