在字符串S1中删除字符串S2中所包含的字符

时间:2021-11-20 19:34:13
 /*************************************************************************
> File Name: test.c
> Author: ToLiMit
> Mail: 348958453@qq.com
> Created Time: Sun 04 Jan 2015 06:20:05 PM PST
************************************************************************/ #include<stdio.h> void delete_str_char (char * main_str, char * sub_str)
{
if ((main_str == NULL) || (sub_str == NULL))
return; char * sub_index = sub_str;
char * main_index = main_str;
char bitmap[] = {};
char * str = (char *)malloc (strlen (main_str) + );
char * index = str;
memset (str, , strlen (main_str) + ); while (*sub_index != '\0') {
char suffix = ((*sub_index) / ) - ;
char offset = (*sub_index) % ; bitmap[suffix] |= (0x1 << ( - offset));
sub_index++;
} while (*main_index != '\0') {
char suffix = ((*main_index) / ) - ;
char offset = (*main_index) % ; if ((bitmap[suffix] & (0x1 << ( - offset))) == ) {
*index = *main_index;
index++;
}
main_index++;
} *index = '\0';
memcpy (main_str, str, strlen (str) + );
free (str);
return;
} int main (int argc, char * argv[])
{
char test[] = "aabcdaaaaabcaacb"; delete_str_char (test, "bcd");
printf ("%s\n", test);
return ;
}

1. 用bitmap标记sub_str中出现过的字符

2. 申请一段buffer, 长度与main_str一致

3. 遍历main_str, 如果字符没有出现在bitmap中, 就将字符写入到buffer中

4. 遍历结束后, buffer中的数据就是删掉了sub_str中出现过的数据

时间复杂度: O(n + m) n为main_str长度, m为sub_str长度

空间复杂度: O(n)