[LeetCode][316. Remove Duplicate Letters] The Detailed Explanation with 3-Steps to Understand the Stack Approach
By Long Luo
This article is the solution The Detailed Explanation with 3-Steps to Understand the Stack Approach of Problem 316. Remove Duplicate Letters .
Intuition
First, let’s look at the problem description:
Given a string \(\textit{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.
The requirements of the problems can be listed in 3 rules:
- Remove duplicate letters;
- The order of characters in the deduplicated string cannot disrupt the relative order of the characters in s;
- Among all deduplicated strings that meet the previous requirement, the one with the smallest lexicographical order is the final result.
Step 1
Let’s just ignore rule 3 for now, and use Stack to follow rule 1 and rule 2:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21public static String removeDuplicateLetters_stk_1(String s) {
Stack<Character> stack = new Stack<>();
boolean[] inStack = new boolean[26];
int len = s.length();
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
if (inStack[ch - 'a']) {
continue;
}
stack.push(ch);
inStack[ch - 'a'] = true;
}
StringBuilder sb = new StringBuilder(stack.size());
while (!stack.empty()) {
sb.append(stack.pop());
}
return sb.reverse().toString();
}
Use the boolean array inStack to record the chars in the stack to deduplication, so the chars in the stack are not duplicated.
If you enter s = “bcabc”, the result is “bca”, which already meets rule 1 and 2. However, the right answer is “abc”.
So if we want to meet the rule 3 and follow the lexicographic order, what should we do?