当前位置: 首页 > news >正文

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:
char* removeDuplicateLetters(char* s) {int len = strlen(s);int lastIndex[26] = {0};  // To store the last occurrence of each characterbool seen[26] = {false};  // To keep track of seen charactersint stackSize = 0;        // To keep track of stack size// Find the last occurrence of each characterfor (int i = 0; i < len; i++) {lastIndex[s[i] - 'a'] = i;}// Array to use as a stackchar* 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 orderwhile (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 seenstack[stackSize++] = current;seen[current - 'a'] = true;}// Null-terminate the result stringstack[stackSize] = '\0';return stack;
}

http://www.mrgr.cn/news/3094.html

相关文章:

  • TCP/IP详解
  • 【问题解决3】【已解决】Cannot determine path to‘tools.jar‘libraryfor17
  • 使用 nginx 搭建代理服务器(正向代理 https 网站)指南
  • vue3+ts封装axios以及解决跨域问题
  • java对象创建的过程
  • 汽车IVI中控OS Linux driver开发实操(二十五):GPIO设备驱动的上手编写
  • 2025舜宇光学校招内推码!!!
  • 设计模式实战:广告管理系统的设计与实现
  • 基于STM32开发的智能家居温控系统
  • JS 获取当前操作系统类型
  • nginx简介及功能介绍
  • 数据库MySQL之事务、索引
  • 设备巡检系统
  • 系统重构新旧流量平滑迁移方案
  • git clone报错unable to access
  • 【kubernetes】k8s配置资源管理
  • 第八季完美童模全球十佳人气超模【刘潇蔓】荣耀加冕 见证星芒风采!
  • PDF.js未按正确的页面顺序显示
  • 【设计模式】观察者模式和订阅发布模式
  • java 数据结构