字符串去重C语言实现

http://blog.csdn.net/zitong_ccnu/article/details/11820511

字符串去重经常会考的笔试题目,这里列出几种常用的方法

更详细的解释(C++版本)请参考http://hawstein.com/posts/1.3.html

解法一:取第一个字符然后遍历后面所有字符,若有重复的则将后面的字符设置为'\0'

[cpp] view plain copy
 
 print?
  1. //将重复字符设置为'\0'  
  2. void RemoveDuplicate(char *str)  
  3. {  
  4.     int i, j, k, len;  
  5.   
  6.     len = strlen(str);  
  7.     for(i = k = 0; i < len; i++)  
  8.     {  
  9.         if(str[i])  
  10.         {  
  11.             str[k++] = str[i];  
  12.             for(j = i + 1; j < len; j++)  
  13.                 if(str[j] == str[i])  
  14.                     str[j] = '\0';  
  15.         }  
  16.     }  
  17.     str[k] = '\0';  
  18. }  

解法二:设置一个标记数组,检查是否有重复字符出现,若没有出现过则插入字符串

[cpp] view plain copy
 
 print?
  1. void RemoveDuplicate(char *s)  
  2. {  
  3.     char check[256] = { 0 };  
  4.     int i, j, len;  
  5.     len = strlen(s);  
  6.     for(i = j = 0; i < len; i++)  
  7.     {  
  8.         if(check[s[i]] == 0)  
  9.         {  
  10.             s[j++] = s[i];  
  11.             check[s[i]] = 1;  
  12.         }  
  13.     }  
  14.     s[j] = '\0';  
  15. }  

进一步优化,这里标记数组用了256个字节,我们可以用含有8个整型元素的数组来表示

[cpp] view plain copy
 
 print?
  1. void RemoveDuplicate(char *s)  
  2. {  
  3.     int i, j, len, remainder;  
  4.     int check[8] = {0};  
  5.     len = strlen(s);  
  6.     for(i = j = 0; i < len; i++)  
  7.     {  
  8.         remainder = s[i] % 32;  
  9.         if((check[s[i] >> 5] & (1 << remainder)) == 0)  
  10.         {  
  11.             s[j++] = s[i];  
  12.             check[s[i] >> 5] |= (1 << remainder);  
  13.         }  
  14.     }  
  15.     s[j] = '\0';  
  16. }  

继续压缩问题,如果字符串中只出现a~z之间的小写字母,可用一个整型变量表示

[cpp] view plain copy
 
 print?
  1. void RemoveDuplicate(char *s)  
  2. {  
  3.     int i, j, val, check;  
  4.     j = check = 0;  
  5.   
  6.     for(i = 0; s[i]; i++)  
  7.     {  
  8.         val = s[i] - 'a';  
  9.         if((check & (1 << val)) == 0)  
  10.         {  
  11.             s[j++] = s[i];  
  12.             check |= 1 << val;  
  13.         }  
  14.     }  
  15.     s[j] = '\0';  
  16. }  

posted on 2017-08-23 12:39  小西红柿  阅读(1854)  评论(0)    收藏  举报

导航