对于三个字符串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
import java.util.*;
public class Mixture {
public boolean chkMixture(String A, int n, String B, int m, String C, int v) {
// write code here
return chkMixture(A,B,C,A.length()-1,B.length()-1,C.length()-1);
}
public static boolean chkMixture(String A,String B, String C,int i,int j,int k){
if(k == 0){
return true;
}
if(i == 0){
if(B.charAt(j) == C.charAt(k)){
return chkMixture(A,B,C,0,j-1,k-1);
}else{
return false;
}
}
if(j == 0){
if(A.charAt(i) == C.charAt(k)){
return chkMixture(A,B,C,i-1,0,k-1);
}else{
return false;
}
}
boolean res1 = false;
boolean res2 = false;
if(A.charAt(i) == C.charAt(k)){
res1 = chkMixture(A,B,C,i-1,j,k-1);
}
if(B.charAt(j) == C.charAt(k)){
res2 = chkMixture(A,B,C,i,j-1,k-1);
}
return res1||res2;
}
}
public static void main(String[] args) throws IOException {
String C = "A12BCC";
String A = "ABCc";
String B = "12C";
Boolean tf=true;
for (int j = 0; j < A.length(); j++) {
int a = C.indexOf(A.substring(j, j + 1));
if (a != -1) {
C = C.substring(0, a) + C.substring(a + 1);
}else{
tf=false;
System.out.println(false);
}
}
for (int j = 0; j < B.length(); j++) {
int a = C.indexOf(B.substring(j, j + 1));
if (a != -1) {
C = C.substring(0, a) + C.substring(a + 1);
}else{
tf=false;
System.out.println(false);
}
}
if(tf)
System.out.println(C.equals(""));
}
直接依次查找
public static boolean mix(String A, String B, String C) {
if(C.length()!=A.length()+B.length()) return false;
int aIndex=0, bIndex=0, aLength=A.length(), bLength=B.length(), cLength=C.length();
for(int cIndex=0;cIndex<cLength;cIndex++) {
char c = C.charAt(cIndex);
if(aIndex < aLength && c==A.charAt(aIndex)) aIndex++;
else if(bIndex < bLength && c==B.charAt(bIndex)) bIndex++;
else return false;
}
return true;
}