7-13 删除重复字符 (20分)


7-13 删除重复字符 (20分)
 

本题要求编写程序,将给定字符串去掉重复的字符后,按照字符ASCII码顺序从小到大排序后输出。

输入格式:

输入是一个以回车结束的非空字符串(少于80个字符)。

输出格式:

输出去重排序后的结果字符串。

输入样例:

ad2f3adjfeainzzzv
 

输出样例:

23adefijnvz

第一种办法:虽然我利用了占坑前移的想法,但是算法还是O(n^2)的 ,不好,可以利用标志变量把它简化为o(n)(指的是不把快排包括在内),
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 int cmp(const void *a,const void *b)
 5 {
 6     return *(char  *)a-*(char *)b;
 7 }
 8 int main()
 9 {
10     int i,j;
11     char  a[100];
12     gets(a);
13     int str=strlen(a);
14     int count;
15     for(i=0;a[i]!='\0';i++)
16     {
17         count=0;
18         for(j=i+1;a[j]!='\0';j++)
19         {
20             if(a[j]!=a[i])
21             a[j-count]=a[j];
22             else
23             count++;
24         }
25         str-=count;
26         a[str]='\0';
27     }
28 
29     qsort(a,str,sizeof(a[0]),cmp);
30     for(i=0;i<str;i++)
31     printf("%c",a[i]);
32     printf("\n");
33     
34     
35     return 0;
36 }

 第二种办法

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int cmp(const void *a,const void *b)
{
    return *(char  *)a-*(char *)b;
}
int main()
{
    int i,j;
    char  a[100];
    int hash[128]={0};
    gets(a);
    int str=strlen(a);
    int count=0;
    for(i=0;a[i]!='\0';i++)
    {
        if(hash[a[i]]!=0)  //说明前面出现过,可以作为坑,给其他人填了
        count++;
        else
        {
        a[i-count]=a[i];
        hash[a[i]]=1;
        }
    }
    str=str-count;
    a[str]=0;
    qsort(a,str,sizeof(a[0]),cmp);
    printf("%s\n",a);


    return 0;
}

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM