利用位图bitmap删除字符串中重复的字母

来源:互联网 发布:巨鹰飞行网络 编辑:程序博客网 时间:2024/05/17 13:12
思想:每个二进制位代表一个字母是否出现。共有8个int类型,即8*4*8=256个二进制位。
      每次置位需要定位某二进制位属于哪个int位:bitmap[c/32] ,然后确定在int中的偏移1 << (c % 32)
需要仔细理解,可单步调试理解之。
#include <stdio.h>#include <string.h>#include <malloc.h>int main(){int i;char *source = "aaabbccdabgf";  //A 65  a 97char *dest;char *temp;unsigned int bitmap[8] = {0,0,0,0,0,0,0,0};unsigned char c;unsigned int mask;dest = (char*)malloc(strlen(source));temp = dest;printf("Before %s\n", source); i=0;while(source[i]){c = source[i];mask = 1 << (c % 32); //mask = 1<<1);if ((bitmap[c/32] & mask) == 0)   //   bitmap[c/32=3] & 2{*temp++ = source[i];bitmap[c/32] |= mask;}i++;}*temp = '\0';     printf("After %s\n", dest);}


原创粉丝点击