Longest string of subroutines

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

Examples can be found on the LeetCode website.

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.

Solution 1: brute force cracking method

Iterate over all possible substrings, and then determine whether the substring is a callback substring, and if so, determine whether it exceeds the current maximum length. Once traversal is complete, the longest callback substring is obtained. This is the first method I came up with. Embarrassingly, the time limit is exceeded after submission in LeetCode. This method is not recommended.

Solution two: dynamic programming

Dynamic programming is more efficient and to be completed.

public class Solution {
    /** * solution 1: brute force method **@param s
     * @return* /
    public static String longestPalindrome(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        String result = String.valueOf(s.charAt(0));
        int max = 1;
        StringBuilder sb;
        for (int i = 0; i < s.length() - 1; i++) {
            sb = new StringBuilder(String.valueOf(s.charAt(i)));
            for (int j = i + 1; j < s.length(); j++) {
                sb.append(s.charAt(j));
                if (checkPalindrome(sb.toString())) {
                    if(sb.length() > max) { result = sb.toString(); max = sb.length(); }}}}return result;
    }

    /** * solution 2: dynamic programming **@param s
     * @return* /
    public static String longestPalindrome2(String s) {
        // TODO:2021/6/7 pending
        return null;
    }

    public static boolean checkPalindrome(String str) {
        if (str == null || str.length() == 1) {
            return true;
        }
        if (str.length() == 2 && str.charAt(0) == str.charAt(1)) {
            return true;
        }
        int count = str.length();
        for (int i = 0; i < count; i++) {
            if(str.charAt(i) ! = str.charAt(count - i -1)) {
                return false; }}return true;
    }

    public static void main(String[] args) {
        // The timeout example is followed by many, many more d's
        System.out.println(longestPalindrome("dddddddd...")); }}Copy the code