2016huasacm暑假集训训练五 C-Common Subsequence
题目链接: https://vjudge.net/contest/126708#problem/C
题意:这是一道求字符串的公共子串的最大长度的题目,用dp动态方程即可
if(a[i]==b[j]) dp[i][j]=dp[i-1][j-1]+1;
else dp[i][j]=(dp[i][j-1]>p[j][i-1]?dp[i][j-1]:p[j][i-1]);
这题主要是要注意两个字符串是同一行输入,题目没说字符串的长度,用c不是dp数组开大了编译不了就是开小了运行错误,错了几次就采用java的字符串来写,因为Java的数组可以根据字符串的长度来开,就不需要担心数组越界或者数组开小了;
AC代码:
1 import java.io.BufferedInputStream; 2 import java.util.Scanner; 3 4 public class Main { 5 static int dp[][]; 6 7 public static void main(String[] args) { 8 9 Scanner s = new Scanner(new BufferedInputStream(System.in)); 10 while (s.hasNext()) { 11 String a = s.next(), b = s.next(); 12 int len1 = a.length(), len2 = b.length(); 13 14 dp = new int[len1 + 1][len2 + 1]; //按字符串的长度开DP数组 15 for (int i = 0; i <= len1; i++) 16 for (int j = 0; j <= len2; j++) 17 dp[i][j] = 0; 18 19 for (int i = 1; i <= len1; i++) 20 for (int j = 1; j <= len2; j++) 21 if (a.charAt(i - 1) == b.charAt(j - 1)) { 22 dp[i][j] = dp[i - 1][j - 1] + 1; 23 } else { 24 dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 25 } 26 System.out.println(dp[len1][len2]); 27 } 28 s.close(); 29 } 30 31 }