bitmap 删除字符串中重复字符

来源:互联网 发布:深圳知豆共享汽车 编辑:程序博客网 时间:2024/06/07 05:57
思想:unsigned int bitmap[8] = {0,0,0,0,0,0,0,0};
一共有 8*sizeof bitmap =256 bits
用这256位记录256个数(unsigned char c的范围)是否出现过
比如65('A') 出现
就把第65位写为1

bitmap的第65位显然应该记录在bitmap[2]中(bitmap[0],bitmap[1]记录了64位)


代码:

int main()
{
  int i;
  char *source = "aaabbccdabgf";  
  
  char *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);  //当前字符对应的到某一bit位 
     // 除以32是因为一个int类型有32个bit,注意bitmap是int数组
     if ((bitmap[c/32] & mask) == 0)   //比较,没有出现过?
     {
       *temp++ = source[i];  //转存到temp变量内
       bitmap[c/32] |= mask;  //对应的标记置位
     }
     i++;
   }

  *temp = '\0'; 
    
  printf("After %s\n", dest);
}

原创粉丝点击