解题思路:
动态规划问题,首先要解决输入一对字符然后计算出结果,所以我这里用
while(sc.hasnext()){ //当有输入的时候就不停止
//直接调用计算的方法然后打印
}
这里我们需要注意到题目要求的是求最大字串,所以
dp[][]比较str1和str2的时候是用Math.max( ... )
注意事项:
动态规划非常需要注意的就是dp数组的大小以及递归逻辑
参考代码:
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
while (sc.hasNext()) {
//传递两个字符串
int sum = number(sc.next(), sc.next());
System.out.println(sum);
}
}
public static int number(String str1, String str2) {
int[][] dp = new int[str1.length() + 1][str2.length() + 1];
for (int i = 0; i <= str1.length(); i++) {
dp[i][0] = 0;
}
for (int j = 0; j <= str2.length(); j++) {
dp[0][j] = 0;
}
for (int i = 1; i <= str1.length(); i++) {
for (int j = 1; j <= str2.length(); j++) {
//当str1[i]==str2[j]的时候,dp值+1
//不等的时候 此时的dp值就是str1和str2对比之下记录的上一个dp值谁最大然后赋值给现在的dp[i][j]
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[str1.length()][str2.length()];
}
}
0.0分
1 人评分
C语言程序设计教程(第三版)课后习题6.7 (C++代码)浏览:1115 |
【出圈】 (C语言代码)用单项循环链表浏览:768 |
C语言考试练习题_保留字母 (C语言代码)浏览:561 |
C语言程序设计教程(第三版)课后习题8.9 (C语言代码)浏览:561 |
P1002 (C语言代码)浏览:970 |
C语言程序设计教程(第三版)课后习题10.1 (Java代码)浏览:1436 |
字符串对比 (C语言代码)浏览:1398 |
WU-陶陶摘苹果2 (C++代码)浏览:968 |
C语言程序设计教程(第三版)课后习题6.5 (C语言代码)浏览:587 |
【求[X,Y]内被除3余1并且被除5余3的整数的和】 (C语言代码)浏览:672 |