小算法汇总

 

1. 在字符串1中删除字符串2中存在的字符

算法思想:尽量使用O(n)而不是O(n2), 由于数组的下标和数组的值之间已经有一层映射关系了,因此利用它可以减少一次遍历,可以将O(n2)降为O(n).由于对于任意一个数字x, bitmap[x/8] |= x%8都能唯一表示,因此算法是成立的!

 1 #include<stdio.h>
 2 #include<string.h> 
 3 #include<stdlib.h> 
 4 
 5 void delete_str_char (char * main_str, char * sub_str)
 6 {
 7     if ((main_str == NULL) || (sub_str == NULL))
 8         return;
 9 
10     char * sub_index = sub_str;
11     char * main_index = main_str;
12     char bitmap[256/8] = {0};
13     char * str = (char *)malloc(strlen(main_str) + 1);
14     char * index = str;
15     memset (str, 0, strlen(str) + 1);
16 
17     while (*sub_index != '\0') {
18         char suffix = ((*sub_index) / 8) - 1;
19         char offset = (*sub_index) % 8;
20 
21         bitmap[suffix] |= (0x1 << (8 - offset));
22         sub_index++;
23     }
24 
25     while (*main_index != '\0') {
26         char suffix = ((*main_index) / 8) - 1;
27         char offset = (*main_index) % 8;
28 
29         if ((bitmap[suffix] & (0x1 << (8 - offset))) == 0) {
30             *index = *main_index;
31             index++;
32         }
33         main_index++;
34     }
35 
36     *index = '\0';
37     memcpy (main_str, str, strlen(str) + 1);
38     free (str);
39     return;
40 }
41 
42 int main (int argc, char * argv[])
43 {
44     char test[] = "aabcdaaaaabcaacfsdfddeddsfandsamdna29131519351905";
45 
46     delete_str_char (test, "bcdef");
47     printf ("%s\n", test);
48     return 0;
49 }

 

2. 删除字符串1中的在字符串2中不存在的字符

只需要将上面的“==”换成“!=”即可

 

posted on 2018-09-11 00:08  Hello-World3  阅读(165)  评论(0编辑  收藏  举报

导航