其他分享
首页 > 其他分享> > 【leetcode】316. 去除重复字母

【leetcode】316. 去除重复字母

作者:互联网

 

char* removeDuplicateLetters(char* s) {
    int vis[26], num[26];
    memset(vis, 0, sizeof(vis));
    memset(num, 0, sizeof(num));

    int n = strlen(s);
    for (int i = 0; i < n; i++) {
        num[s[i] - 'a']++;
    }

    char* stk = malloc(sizeof(char) * 27);
    int stkTop = 0;
    for (int i = 0; i < n; i++) {
        if (!vis[s[i] - 'a']) {
            while (stkTop > 0 && stk[stkTop - 1] > s[i]) {
                if (num[stk[stkTop - 1] - 'a'] > 0) {
                    vis[stk[--stkTop] - 'a'] = 0;
                } else {
                    break;
                }
            }
            vis[s[i] - 'a'] = 1;
            stk[stkTop++] = s[i];
        }
        num[s[i] - 'a'] -= 1;
    }
    stk[stkTop] = '\0';
    return stk;
}

 

标签:int,stkTop,316,stk,char,vis,num,去除,leetcode
来源: https://www.cnblogs.com/ganxiang/p/14284195.html