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;
}
相关推荐
甄心爱学习8 分钟前
【最优化】1-6章习题
人工智能·算法
PD我是你的真爱粉9 分钟前
向量数据库原理与检索算法入门:ANN、HNSW、LSH、PQ 与相似度计算
数据库·人工智能·算法
汀、人工智能11 分钟前
[特殊字符] 第72课:杨辉三角
数据结构·算法·数据库架构·图论·bfs·杨辉三角
_深海凉_20 分钟前
LeetCode热题100- 字母异位词分组
leetcode
洛水水22 分钟前
【力扣100题】14.两数相加
c++·算法·leetcode
我不是小upper24 分钟前
相关≠因果!机器学习中皮尔逊相关检验的完整流程
人工智能·算法·机器学习
float_com25 分钟前
LeetCode80. 删除有序数组中的重复项 II
leetcode
pwn蒸鱼26 分钟前
leetcode:21. 合并两个有序链表
算法·leetcode·链表
洛水水28 分钟前
【力扣100题】15.删除链表的倒数第 N 个结点
算法·leetcode·链表
范纹杉想快点毕业32 分钟前
Zynq开发视角下的C语言能力分级详解
c语言·开发语言