LeetCode //C - 316. Remove Duplicate Letters

316. Remove Duplicate Letters

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

Example 1:

Input: s = "bcabc"
Output: "abc"

Example 2:

Input: s = "cbacdcbc"
Output: "acdb"

Constraints:
  • 1 < = s . l e n g t h < = 1 0 4 1 <= s.length <= 10^4 1<=s.length<=104
  • s consists of lowercase English letters.

From: LeetCode

Link: 316. Remove Duplicate Letters


Solution:

Ideas:

1. lastIndex\[\]: This array stores the last occurrence of each character in the input string s.

2. seen\[\]: This boolean array keeps track of which characters are already included in the stack (result).

3. stack: This array is used as a stack to build the result string with the smallest lexicographical order.

4. Algorithm:

  • Traverse through each character in the string s.
  • Skip the character if it is already in the result.
  • Otherwise, pop characters from the stack if they are lexicographically greater than the current character and if they appear later in the string.
  • Push the current character onto the stack and mark it as seen.

5. The final stack contains the result, which is then null-terminated and returned as the result string.

Code:
c 复制代码
char* removeDuplicateLetters(char* s) {
    int len = strlen(s);
    int lastIndex[26] = {0};  // To store the last occurrence of each character
    bool seen[26] = {false};  // To keep track of seen characters
    int stackSize = 0;        // To keep track of stack size
    
    // Find the last occurrence of each character
    for (int i = 0; i < len; i++) {
        lastIndex[s[i] - 'a'] = i;
    }
    
    // Array to use as a stack
    char* stack = (char*)malloc((len + 1) * sizeof(char));
    
    for (int i = 0; i < len; i++) {
        char current = s[i];
        if (seen[current - 'a']) continue;  // Skip if character is already in the result
        
        // Ensure the smallest lexicographical order
        while (stackSize > 0 && stack[stackSize - 1] > current && lastIndex[stack[stackSize - 1] - 'a'] > i) {
            seen[stack[--stackSize] - 'a'] = false;
        }
        
        // Add current character to the stack and mark it as seen
        stack[stackSize++] = current;
        seen[current - 'a'] = true;
    }
    
    // Null-terminate the result string
    stack[stackSize] = '\0';
    
    return stack;
}
相关推荐
rhythm-ring5 小时前
宏定义续行符 \ 的使用与踩坑
c语言·c++
AI情绪识别开源6 小时前
检信 AI 智能推广平台(代号:JX-Promote)
人工智能·算法·erlang
老当益壮梁奶奶6 小时前
Linux软件编程学习笔记(八):进程间通信详解(1)
linux·c语言·笔记·学习·算法
「QT(C++)开发工程师」6 小时前
C++11 std::unique_ptr — 独占所有权的智能指针
c语言·开发语言·c++·qt
不会就选b7 小时前
算法日常・每日刷题--<BFS拓扑排序>4
算法
不正经学生7 小时前
C语言动态内存管理(上):堆上的自由与责任
c语言·开发语言·c++·算法·面试
伟大的车尔尼7 小时前
贪心的概念
数据结构·算法·贪心
方方洛7 小时前
vllm教程-00-前言与导读
人工智能·算法·vllm
IT毕设实战小研7 小时前
电影数据可视化推荐系统
大数据·后端·爬虫·python·算法·信息可视化·课程设计
且随疾风前行.7 小时前
从驱动来分析服务的添加过程
算法