1. Title Description

Given a string s, find the longest substring in s.

Example 1:

Input: s = “babad” Output: “bab” Explanation: “ABA” is also the answer to the question. Example 2:

Input: s = “CBBD” Output: “bb” Example 3:

Input: s = “a” Output: “a” Example 4:

Input: s = “AC”

Tip:

1 <= S. length <= 1000 s Consists of only digits and letters (uppercase and/or lowercase)

Source: LeetCode link: leetcode-cn.com/problems/lo… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Second, complete code

public class Solution {

    public static void main(String[] args) {

        String test_data = "ba1221";
        System.out.println(longestPalindrome(test_data));
        
    }


    public static String longestPalindrome(String s) {
        // Save the callback substring
        String sub_longest_str = "";
        int s_length = s.length();

        if (s_length < 1 || s_length > 1000) {
            return sub_longest_str;
        }

        if (s_length == 1) {
            return s;
        }

        for (int i = 0; i < s_length; i++) {

            String s1 = find_palindrome(s, i, i);

            String s2 = find_palindrome(s, i, i + 1);

            sub_longest_str = sub_longest_str.length() > s1.length() ? sub_longest_str : s1;
            sub_longest_str = sub_longest_str.length() > s2.length() ? sub_longest_str : s2;

        }
        return sub_longest_str;
    }

    private static String find_palindrome(String s, int i, int j) {
        while (i >= 0 && j < s.length()) {
            if(s.charAt(i) ! = s.charAt(j)) {break;
            } else{ i--; j++; }}return s.substring(i + 1, j); }}Copy the code