lotus

贵有恒何必三更眠五更起 最无益只怕一日曝十日寒

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. 题目

读题

 HJ75 公共子串计算

 

考查点

 同   HJ65 查找两个字符串a,b中的最长公共子串

HJ65 查找两个字符串a,b中的最长公共子串

2. 解法

思路

 

代码逻辑

 

具体实现

 自行实现

public class HJ075 {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println(dp(sc.nextLine(), sc.nextLine()));
}

public static int dp(String str1, String str2) {

int m = str1.length();
int n = str2.length();
int[][] dp = new int[m][n];

int maxLen = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
dp[i][j] = str1.charAt(0) == str2.charAt(0) ? 1 : 0;
} else if (i == 0) {
dp[i][j] = str1.charAt(0) == str2.charAt(j) ? 1 : 0;
} else if (j == 0) {
dp[i][j] = str1.charAt(i) == str2.charAt(0) ? 1 : 0;
} else {
if (str1.charAt(i) == str2.charAt(j)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = 0;
}
}

if (dp[i][j] > maxLen) {
maxLen = dp[i][j];
}
}

}
return maxLen;


}
}

 

3. 总结

posted on 2023-07-21 19:48  白露~  阅读(83)  评论(0编辑  收藏  举报