题目描述
给定两个字符串s1 和 s2,返回 使两个字符串相等所需删除字符的 ASCII 值的最小和 。
示例
思路
代码如下
解法一
public int minimumDeleteSum1 ( String s1, String s2) {
int m = s1. length ( ) , n = s2. length ( ) ;
int [ ] [ ] dp = new int [ m + 1 ] [ n + 1 ] ;
int res = 0 ;
for ( char c : s1. toCharArray ( ) ) {
res += c;
}
for ( char c : s2. toCharArray ( ) ) {
res += c;
}
for ( int i = 1 ; i < dp. length; i++ ) {
for ( int j = 1 ; j < dp[ 0 ] . length; j++ ) {
if ( s1. charAt ( i - 1 ) == s2. charAt ( j - 1 ) ) {
dp[ i] [ j] = dp[ i - 1 ] [ j - 1 ] + s1. charAt ( i - 1 ) * 2 ;
} else {
dp[ i] [ j] = Math . max ( dp[ i - 1 ] [ j] , dp[ i] [ j - 1 ] ) ;
}
}
}
return res - dp[ m] [ n] ;
}
解法二
public int minimumDeleteSum ( String s1, String s2) {
int m = s1. length ( ) , n = s2. length ( ) ;
int [ ] [ ] dp = new int [ m + 1 ] [ n + 1 ] ;
for ( int i = 1 ; i < m + 1 ; i++ ) {
dp[ i] [ 0 ] = dp[ i - 1 ] [ 0 ] + s1. charAt ( i - 1 ) ;
}
for ( int i = 1 ; i < n + 1 ; i++ ) {
dp[ 0 ] [ i] = dp[ 0 ] [ i - 1 ] + s2. charAt ( i - 1 ) ;
}
for ( int i = 1 ; i < dp. length; i++ ) {
for ( int j = 1 ; j < dp[ 0 ] . length; j++ ) {
if ( s1. charAt ( i - 1 ) == s2. charAt ( j - 1 ) ) {
dp[ i] [ j] = dp[ i - 1 ] [ j - 1 ] ;
} else {
dp[ i] [ j] = Math . min ( dp[ i - 1 ] [ j] + s1. charAt ( i - 1 ) , dp[ i] [ j - 1 ] + s2. charAt ( j - 1 ) ) ;
}
}
}
return dp[ m] [ n] ;
}