题解 | #公共子串计算#

公共子串计算

http://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b

使用动态规划进行求解,先确定边界条件,递推式如下:

dp[i][j] = s1[i]==s2[j] ? dp[i-1][j-1] + 1 : 0

/**
dp[i][j]表示字符串s1[0:i]和s2[0:j]的公共子串长度,公共子串包含i,j

dp[i][j] = s1[i]==s2[j] ? dp[i-1][j-1] + 1 : 0

*/

import java.util.*;

public class Main{
    
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String s1 = sc.nextLine();
            String s2 = sc.nextLine();
            int len = maxCommonSubstringLen(s1,s2);
            System.out.println(len);
        }
    }
    
    public static int maxCommonSubstringLen(String s1, String s2){
        int m = s1.length(), n = s2.length();
        if(m == 0 || n == 0){
            return 0;
        }
        int[][] dp = new int[m][n];
        //边界条件
        //dp[i][0]
        for(int i = 0; i < m; i++){
            dp[i][0] = s1.charAt(i) == s2.charAt(0) ? 1 : 0;
        }
        //dp[0][i]
        for(int i = 0; i < n; i++){
            dp[0][i] = s1.charAt(0) == s2.charAt(i) ? 1 : 0;
        }
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                if(s1.charAt(i) == s2.charAt(j)){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }
            }
        }
        int maxLen = 0;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                maxLen = Math.max(dp[i][j], maxLen);
            }
        }
        return maxLen;
    }
    
}
全部评论

相关推荐

1 3 评论
分享
牛客网
牛客企业服务