首页 > 试题广场 >

字符串A和字符串B,请将A中在B中存在的字符删除,比如A="

[问答题]
字符串A和字符串B,请将A中在B中存在的字符删除,比如A="This is the world",B="abcdefghi",则返回A为"Ts s t worl"
推荐
arron回答三风格(解释/代码/结果),
   考虑大小写情况,
   利用线性hash制作bitmap,使复杂度将为o(M+N),不是传统的o(M*N)
   字符串的比较是基础。


上代码,这里利用线性hash优化为复杂度为n

char * removeStr(char *A, char *B)
{//大小写相关的话
 int bitMapAll[26][2]={0};//ascii 0:0x31 ,A:0x41, B:0x61 
 if(A == NULL) return NULL ; 
 if(B==NULL) return NULL;
 while (*B!='\0')
 {
 if (  (*B>='A' &&*B<='Z' ) )
 bitMapAll[(*B)-'A'][1]=1;
 else if  (*B>='a' &&*B<='z' )  
 bitMapAll[(*B)-'a'][0]=1;
 B++;
 }
 char *temp=new char[strlen(A)];//A;//destory it
 int cnt=0;
 while (*A!='\0')
 {
 if  (*A>='A' &&*A<='Z' ) 
 if(bitMapAll[(*A)-'A'][1])//if(bitMapAll[*A+'A'-'a'])
 {
 A++;
 continue;
 }
 if (*A>='a' && *A<='z')
 if(bitMapAll[(*A)-'a'][0])
 {
 A++;;
 continue;
 };
 cnt++;
 *temp=*A;
 A++;
 temp++;

 }
 *temp ='\0';
 return temp-cnt;
}
//40minutes:
//bitmap complex ;

int main()//o(N)
{//"This is the world",B="abcdefghi" ,===>A="Ts s t worl"
 char mA[]="This is the world";
 char mB[]="abcdefghi";
 char *A=mA,*B=mB;
 A=removeStr(A,B);
 printf("%s\n",A);
 system("pause");
 delete A;
 return 0;
}

编辑于 2015-02-09 00:33:38 回复(0)
function arron(a, b){
    var tmp = '';
    for(var i = 0; i < a.length;i++){
        for(var j = 0; j < b.length; j++){
            if(!a[i].includes(b[j])){                               
                if(j + 1 === b.length){
                    tmp += a.charAt(i);
                }
                continue;
            }
            break;
        }
    }
    console.log('a = ' + tmp);
}
var a = 'This is the world';
var b = 'abcdefghi';
arron(a, b);

发表于 2017-09-18 16:02:50 回复(0)
public String del(String sourceString, String delString) {
    String result = "";
    for (int i = 0; i < sourceString.length(); i++) {
        if (!delString.contains(sourceString.charAt(i)+"")) {
            result += sourceString.charAt(i);
        }
    }
    return result;
}

发表于 2015-01-14 17:40:33 回复(0)