Niuke.net brushing questions-the longest common substring

Problem Description

Given two strings str1 and str2, output the longest common substring of the two strings. If the longest common substring is empty, output -1.

Input description:
input two strings

Output description:
output the longest common substring

Example

Example 1

Enter
"1AB2345CD", "12345EF"

Output
"2345"

Solutions

analysis

  1. The longest common subsequence (Longest Common Subsequence, LCS for short) is a very classic interview question, because its solution is a typical two-dimensional dynamic programming, and most of the more difficult string problems follow this question.
  2. Method introduction
    (1) The definition of dp array: int[][] dp = new int[m + 1][n + 1]; The value of the array is the length of the common string
    (2) The assignment of a two-dimensional array:
    Insert picture description here
    (3 ) It can be seen from the chart that the length formula of the longest common string is: dp[i + 1][j + 1] = dp[i][j] + 1

method

  1. Use two-dimensional dynamic programming + some optimizations.

Code

// 思路1
public class Solution {
    
      
    public String LCS (String str1, String str2) {
    
    
        // write code here
        int m = str1.length(), n = str2.length();
        int[][] dp = new int[m + 1][n + 1];

		// 记录最长公共字串的长度
        int maxLen = 0;
        int index = 0;
        for (int i = 0; i < m; i++) {
    
    
            for (int j = 0; j < n; j++) {
    
    
                // 获取两个串字符
                char c1 = str1.charAt(i), c2 = str2.charAt(j);
                if (c1 == c2) {
    
    
                    // 运用二维动态规划总结的公式
                    dp[i + 1][j + 1] = dp[i][j] + 1;
                    if (dp[i + 1][j + 1] > maxLen) {
    
    
                        maxLen = dp[i + 1][j + 1];
                        // 记录最长公共字串结束的索引
                        index = j + 1;
                    }
                }
            }
        }

        if (maxLen == 0) {
    
    
            return "";
        }

        return str2.substring(index - maxLen, index);
    }
}

Time complexity analysis:
O(MN): Two-layer loop, traversing the string, so the time complexity is the product of the length of the string.

Space complexity analysis:
O(MN): An additional two-dimensional array is used to store the length of the longest common string, (m+1)(n+1) = mn + m + n + 1, m and n can be ignored The law is constant, so the space complexity is MN.

If you want to test, you can go directly to the link of Niuke.com to do the test

The longest public substring

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/113758113