对于三个字符串A,B,C。我们称C由A和B交错组成当且仅当C包含且仅包含A,B中所有字符,且对应的顺序不改变。请编写一个高效算法,判断C串是否由A和B交错组成。
给定三个字符串A,B和C,及他们的长度。请返回一个bool值,代表C是否由A和B交错组成。保证三个串的长度均小于等于100。
"ABC",3,"12C",3,"A12BCC",6
返回:true
class Mixture {
public:
bool chkMixture(string A, int n, string B, int m, string C, int v) {
// write code here
if ( v == n && A == C ) return true ;
if ( !v ) return false ;
if ( v == m && B == C ) return true ;
else if ( v == m ) return false ;
if ( v == n && A == C ) return true ;
else if ( v == n ) return false ;
vector> vec( n + 1, vector( m + 1, false ) ) ;
vec[0][0] = true ;
for ( int i = 1; i <= n; ++ i ) {
if ( C[i - 1] == A[i - 1] ) {
vec[i][0] = vec[i - 1][0] ;
}
}
for ( int i = 1; i <= m; ++ i ) {
if ( C[i - 1] == B[i - 1] ) {
vec[0][i] = vec[0][i - 1] ;
}
}
for ( int i = 1; i <= n; ++ i ) {
for ( int j = 1; j <= m; ++ j ) {
if ( !vec[i][j] && A[i - 1] == C[i + j - 1] ) {
vec[i][j] = vec[i - 1][j] ;
}
if ( !vec[i][j] && B[j - 1] == C[i + j - 1] ) {
vec[i][j] = vec[i][j - 1] ;
}
}
}
return vec[n][m] ;
}
};
第二次做:
class Mixture {
public:
bool chkMixture(string A, int n, string B, int m, string C, int v) {
// write code here
if ( !v ) return false ;
if ( C == A && n == v ) return true ;
else if ( n == v ) return false ;
if ( C == B && m == v ) return true ;
else if ( m == v ) return false ;
vector> vec( A.size() + 1, vector( B.size() + 1, false ) ) ;
vec[0][0] = true ;
for ( int i = 1; i <= A.size(); ++ i ) {
if ( C[i - 1] == A[i - 1] ) vec[i][0] = vec[i - 1][0] ;
}
for ( int i = 1; i <= B.size(); ++ i ) {
if ( C[i - 1] == B[i - 1] ) vec[0][i] = vec[0][i - 1] ;
}
for ( int i = 1; i <= A.size(); ++ i ) {
for ( int j = 1; j <= B.size(); ++ j ) {
if ( !vec[i][j] && A[i - 1] == C[i + j - 1] ) vec[i][j] = vec[i - 1][j] ;
if ( !vec[i][j] && B[j - 1] == C[i + j - 1] ) vec[i][j] = vec[i][j - 1] ;
}
}
return vec[n][m] ;
}
};