题目描述
现在有两个字符串,可以在字符串的任意位置(开头,中间,末尾)插入任意数量的空格.
在插入适当数量的空格后,将两个字符串右对齐,通过一定的规则获得一个匹配值X,你的任务是寻找一种方案,使得匹配值X最大.
匹配值的计算规则是:
1.对每一个匹配的位置(对应位置字符相同),X+=2;
2.对每一段连续的空格,X-=1;
也即匹配值X是匹配位置的2倍减去连续空格的段数.
注意并不处罚左边的不匹配位置.
解答要求时间限制:1000ms, 内存限制:256MB
输入
每个输入样例包括两行,每行包含一个字符串,最长500个字符.每个字符串保证只包含大写英文字母.
输出
每个样例的输出仅包含一个整数,表示最大的匹配值X.
样例
输入样例 1 复制
AADDEFGGHC ADCDEGH
输出样例 1
9
//We have imported the necessary tool classes.
//If you need to import additional packages or classes, please import here.
public class Main
{
public static void main(String[] args)
{
//please define the JAVA input here. For example: Scanner s = new Scanner(System.in);
//please finish the function body here.
//please define the JAVA output here. For example: System.out.println(s.nextInt());
Scanner sc = new Scanner(System.in);
char[] ch1 = sc.nextLine().toCharArray();
char[] ch2 = sc.nextLine().toCharArray();
int dp[][] = new int[501][501];
int n = ch1.length>ch2.length?ch1.length:ch2.length;
for(int i =0;i<ch1.length;i++){
for(int j= 0;j<ch2.length;j++){
if(i == 0 || j == 0)dp[i][j] = ((ch1[i]==ch2[j])?2:0);
else dp[i][j] = dp[i-1][j-1] + ((ch1[i]==ch2[j])?2:0);
for(int k = 0; k < i; k++)dp[i][j] = Math.max(dp[i][j], (dp[k][j]-1));
for(int k = 0; k < j; k++)dp[i][j] = Math.max(dp[i][j], (dp[i][k]-1));
}
}
System.out.println(dp[ch1.length-1][ch2.length-1]);
}
}