This approach uses a stack to build the resultant string such that it is the smallest lexicographical order. We will also use an array to keep count of each character’s frequency and a boolean array to track the characters that have been added to the stack. As we iterate over each character, we decide whether to add it to the stack or skip it based on the frequency and lexicographical conditions.
Time Complexity: O(n), where n is the length of the string, as each character is pushed and popped from the stack at most once.
Space Complexity: O(1), because the stack contains at most 26 characters, and other auxiliary data structures are of constant size.
1#include <iostream>
2#include <string>
3#include <vector>
4#include <stack>
5using namespace std;
6
7string removeDuplicateLetters(string s) {
8 vector<int> freq(26, 0);
9 vector<bool> inStack(26, false);
10 for (char c : s) freq[c - 'a']++;
11 stack<char> result;
12 for (char c : s) {
13 freq[c - 'a']--;
14 if (inStack[c - 'a']) continue;
15 while (!result.empty() && result.top() > c && freq[result.top() - 'a'] > 0) {
16 inStack[result.top() - 'a'] = false;
17 result.pop();
18 }
19 result.push(c);
20 inStack[c - 'a'] = true;
21 }
22 string res;
23 while (!result.empty()) {
24 res = result.top() + res;
25 result.pop();
26 }
27 return res;
28}
29
30int main() {
31 string s = "cbacdcbc";
32 cout << removeDuplicateLetters(s) << endl;
33 return 0;
34}In this C++ solution, we make use of a stack to store the characters of the result string. We use vectors to keep track of character frequencies and presence in the stack. Characters are pushed onto or popped from the stack based on the conditions provided.
This approach focuses on iteratively constructing the result string while ensuring that the result remains lexicographically smallest by checking each character and including it in the result only if it meets certain frequency and order criteria.
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(1), considering character storage is bounded to a maximum of 26.
1
In this solution, a character set is updated via a general loop to progressively add elements to the result string. This method leverages frequency checks of character availability while ensuring characters are not redundant in the result.