牛客网编程高频题22——NC127最长公共子串

目录

最长公共子串

描述

示例1

输入

返回值

备注:

方法:动态规划


最长公共子串

描述

给定两个字符串str1和str2,输出两个字符串的最长公共子串,

题目保证str1和str2的最长公共子串存在且唯一

示例1

输入

"1AB2345CD","12345EF"

返回值

"2345"

备注:

1\le str_1,str_2\le5000

方法:动态规划

import java.util.*;

public class Solution {
    public String LCS (String str1, String str2) {
        // write code here
        int len_str1=str1.length(),len_str2=str2.length();
        int dp[][]=new int[len_str1+1][len_str2+1];
        int max=0,index=0;
        for (int i = 0; i < len_str1; i++) {
            for (int j = 0; j < len_str2; j++) {
                if(str1.charAt(i)==str2.charAt(j)){
                    dp[i+1][j+1]=dp[i][j]+1;
                    if (max<dp[i+1][j+1]){
                        max=dp[i+1][j+1];
                        index=i+1;
                    }
                }
            }
        }
        return max>0?str1.substring(index-max,index):"";
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_39478524/article/details/117409640