首页 > 技术文章 > 删除一个字符串中出现次数最少的字符

babysunnie 2013-07-28 12:14 原文

  • ** 题目:删除一个字符串中出现次数最少的字符,函数原型为: 
  • ** 
  • **       char *  delChar(char *s,int iLen)      
  • **      
  • **       其中 s为输入字符串,iLen为输入字符串长度。 
  • **        
  • **       如输入字符串为“abcdd”,输出为"dd"。 
  • **          
  • **       字符串中只有小写字母,不含空格且字符串最大长度不超过20。 
  • **/  
/**
**
** 题目:删除一个字符串中出现次数最少的字符,函数原型为:
**
**       char *  delChar(char *s,int iLen)     
**	   
**		 其中 s为输入字符串,iLen为输入字符串长度。
**		 
**	     如输入字符串为“abcdd”,输出为"dd"。
**		   
**		 字符串中只有小写字母,不含空格且字符串最大长度不超过20。
**/

方法一:

  1. #include <stdio.h>      
  2. #include <string.h>      
  3. #include <malloc.h>      
  4.     
  5. char * delChar(char *s,int iLen)    
  6. {    
  7.     if((s == NULL) || iLen <= 0)    
  8.     {    
  9.         return NULL;    
  10.     }    
  11.     int i;    
  12.     /*定义能够长度为26的数组*/    
  13.     const int MAXLEN = 26;    
  14.     /*min表示字符串中字符最少的数目*/    
  15.     /*数组nCountTable分别存储当前字符串中存在的字符数目,不存在则为0*/    
  16.     unsigned int min,nCountTable[MAXLEN];    
  17.     /*初始化为0*/    
  18.     for(i = 0;i < MAXLEN;i ++)    
  19.     {    
  20.         nCountTable[i] = 0;    
  21.     }    
  22.     /*统计当前字符串中各个字符的数目*/    
  23.     for(i = 0;i < iLen;i ++)    
  24.     {    
  25.         nCountTable[*(s + i) - 'a'] ++;    
  26.     }    
  27.     /*把nCountTable数组中第一个不为0的,作为第一个数,用于找出最少的个数*/    
  28.     while(nCountTable[i] == 0)    
  29.     {    
  30.         i ++;    
  31.     }    
  32.     min = nCountTable[i];    
  33.     /*找出字符数目最少的那个数,不存在的不算入其中*/    
  34.     for(i = 0;i < MAXLEN;i ++)    
  35.     {    
  36.         if(nCountTable[i] != 0)    
  37.         {    
  38.             if(nCountTable[i] < min)    
  39.             {    
  40.                 min = nCountTable[i];    
  41.             }    
  42.         }               
  43.     }    
  44.     /*删除字符串中最少的字符,并且返回*/    
  45.     char *pSlow = s;  
  46.     char *pFast = s;      
  47.     while(*pFast != '\0')    
  48.     {    
  49.         if(nCountTable[*pFast - 'a'] != min)    
  50.         {    
  51.             *pSlow = *pFast;     
  52.             pSlow ++;  
  53.         }           
  54.         pFast ++;  
  55.     }    
  56.     *pSlow = '\0';  
  57.     
  58.     return s;    
  59. }    
  60. int main()    
  61. {    
  62.     char str[] = "abadccdehigiktk";    
  63.     int iLen = strlen(str)/sizeof(char);    
  64.     char *tmp = delChar(str,iLen);    
  65.     printf("%s\n",tmp);    
  66. }    

推荐阅读