TypechoJoeTheme

IT技术分享

统计

[LeetCode 316] Remove Duplicate Letters [C] [Runtime : 3 MS]

2017-07-06
/
0 评论
/
707 阅读
/
正在检测是否收录...
07/06

1. Runtime Distribution

2. Submission Details

3. Description

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.

4. Example

Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "acdb"

5. Code

char* removeDuplicateLetters(char* s) {

    int remain_count[128];
    int result_has[128];

    for(int i = 97; i< 128; i++)
    {
        remain_count[i] = 0;
        result_has[i] = 0;
    }

    int length = strlen(s);

    for(int i = 0; i< length; i++)
    {
        remain_count[s[i]] ++;
    }

    char* stack = malloc(sizeof(char)*length);

    int top = 0;

    for(int i = 0; i< length; i++)
    {
        while(top > 0)
        {
            if(stack[top -1] < s[i] || remain_count[stack[top - 1]] == 0 || result_has[s[i]])
            {
                break;
            }
            result_has[stack[top - 1]] --;
            top--;
        }

        if(!result_has[s[i]])
        {
            stack[top++] = s[i];
            result_has[s[i]] ++;
        }

        remain_count[s[i]] --;
    }

    stack[top] = '\0';
    return stack;
}
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

char* removeDuplicateLetters(char* s) {

    int remain_count[128];
    int result_has[128];

    for(int i = 97; i< 128; i++)
    {
        remain_count[i] = 0;
        result_has[i] = 0;
    }

    int length = strlen(s);

    for(int i = 0; i< length; i++)
    {
        remain_count[s[i]] ++;
    }

    char* stack = malloc(sizeof(char)*length);

    int top = 0;

    for(int i = 0; i< length; i++)
    {
        while(top > 0)
        {
            if(stack[top -1] < s[i] || remain_count[stack[top - 1]] == 0 || result_has[s[i]])
            {
                break;
            }
            result_has[stack[top - 1]] --;
            top--;
        }

        if(!result_has[s[i]])
        {
            stack[top++] = s[i];
            result_has[s[i]] ++;
        }

        remain_count[s[i]] --;
    }

    stack[top] = '\0';
    return stack;
}

int main()
{
    char *s = "abacb\0";
    char * result = removeDuplicateLetters(s);
    puts(result);
    system("pause");
    return 0;
}
Stack
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/499/(转载时请注明本文出处及文章链接)