316. Remove Duplicate Letters
Problem
Tags: String
, Stack
, Greedy
, Monotonic Stack
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.length <= 10^4
s
consists of lowercase English letters.
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
Code
C
// 316. Remove Duplicate Letters (9/10/54180)
// Runtime: 0 ms (94.51%) Memory: 5.68 MB (90.11%)
char* removeDuplicateLetters (char* s) {
int last_pos[26] = { -1 };
for (int i = 0; s[i] != '\0'; i++) {
last_pos[s[i] - 'a'] = i;
}
bool used[26] = { false };
int stk[10001] = { 0 };
int stk_size = 0;
for (int i = 0; s[i] != '\0'; i++) {
int code = s[i] - 'a';
if (used[code]) {
continue;
}
while (stk_size) {
int prev = stk[stk_size - 1];
if (prev < code || i >= last_pos[prev]) {
break;
}
stk_size--;
used[prev] = false;
}
stk[stk_size++] = code;
used[code] = true;
}
char* ans = (char*)calloc(stk_size + 1, sizeof(char));
for (int i = 0; i < stk_size; i++) {
ans[i] = stk[i] + 'a';
}
return ans;
}