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;
}
相关推荐
诚丞成7 分钟前
滑动窗口篇——如行云流水般的高效解法与智能之道(1)
算法
带多刺的玫瑰2 小时前
Leecode刷题C语言之统计不是特殊数字的数字数量
java·c语言·算法
爱敲代码的憨仔2 小时前
《线性代数的本质》
线性代数·算法·决策树
yigan_Eins2 小时前
【数论】莫比乌斯函数及其反演
c++·经验分享·算法
阿史大杯茶2 小时前
AtCoder Beginner Contest 381(ABCDEF 题)视频讲解
数据结构·c++·算法
陌小呆^O^2 小时前
Cmakelist.txt之win-c-udp-server
c语言·开发语言·udp
დ旧言~3 小时前
【高阶数据结构】图论
算法·深度优先·广度优先·宽度优先·推荐算法
时光の尘3 小时前
C语言菜鸟入门·关键字·float以及double的用法
运维·服务器·c语言·开发语言·stm32·单片机·c
张彦峰ZYF3 小时前
投资策略规划最优决策分析
分布式·算法·金融
-一杯为品-3 小时前
【51单片机】程序实验5&6.独立按键-矩阵按键
c语言·笔记·学习·51单片机·硬件工程