《leetCode》:Remove Duplicate Letters

本文介绍了一个去除字符串中重复字母的方法,确保每个字母只出现一次,并且结果字符串在字典序上是最小的。通过使用贪婪算法,实现了字符的正确排序。

题目

Given a string which contains only lowercase letters, remove duplicate 
letters so that every letter appear once and only once. 
You must make sure your result is the smallest in lexicographical order among all possible results.

Example:
Given "bcabc"
Return "abc"

Given "cbacdcbc"
Return "acdb"

思路

利用贪婪的思想,尽可能的将小的放在前面。

实现代码如下:

char* removeDuplicateLetters(char* s) {
    if(s==NULL){
        return NULL;
    }
    int spaceLen=26;
    int *count=(int *)malloc(spaceLen*sizeof(int));//用来统计字符串s中每个字符出现的次数 
    if(count==NULL){
        exit(EXIT_FAILURE);
    }
    memset(count,0,spaceLen*sizeof(int));//初始化为零
    int len=strlen(s);
    for(int i=0;i<len;i++){
        count[s[i]-'a']++;
    }
    //将flag中为true的字符组合起来返回即可
    //开辟一段空间来保存结果
    char *res=(char *)malloc(spaceLen*sizeof(char));
    if(res==NULL){
        exit(EXIT_FAILURE);
    }
    bool *isExistInRes=(bool *)malloc(spaceLen*sizeof(bool));//用来标识结果是否已经存在了该字符 
    if(isExistInRes==NULL){
        exit(EXIT_FAILURE);
    } 
    memset(isExistInRes,false,spaceLen*sizeof(bool));//注意:一定要初始化为false

    char ch;
    char sc;
    int end=-1;
    for(int i=0;i<len;i++){
        ch=s[i];
        if(isExistInRes[ch-'a']){
            count[ch-'a']--;
            continue;
        }
        //通过判断刚加入的这个元素是否应该加入,如果后面的元素小于刚刚加入的元素并且这个元素不是最后一次出现,则应该不加入 
        while(end>=0&&((sc=res[end])>=ch)&&count[sc-'a']>0){
            end--;
            isExistInRes[sc-'a']=false;
        }
        res[++end]=ch;
        count[ch-'a']--;
        isExistInRes[ch-'a']=true; 

    }
    res[++end]='\0';
    return res;    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值