316 Remove Duplicate Letters

1. Question

Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example:
Given"bcabc" Return"abc"
Given"cbacdcbc" Return"acdb"

2. Implementation

思路:由于题目要求输出的结果是smallest in lexicographical order among all possible results,所以考虑用单调栈保持输出结果的单调性。用两个数组count和visited表示当前字符的剩余数量和是否被拜访过,如果栈顶上的字符大于当前字符且且当前字符的剩余量不为0,说明我们现在不需要栈顶的字符,可以以后再加上保持单调性
1
class Solution {
2
public String removeDuplicateLetters(String s) {
3
int[] count = new int[256];
4
boolean[] visited = new boolean[256];
5
Stack<Character> stack = new Stack<>();
6
7
for (char c : s.toCharArray()) {
8
++count[c];
9
}
10
11
for (char c : s.toCharArray()) {
12
--count[c];
13
14
if (visited[c]) {
15
continue;
16
}
17
18
while (!stack.isEmpty() && stack.peek() > c && count[stack.peek()] != 0) {
19
visited[stack.peek()] = false;
20
stack.pop();
21
}
22
23
stack.push(c);
24
visited[c] = true;
25
}
26
27
StringBuilder res = new StringBuilder();
28
while (!stack.isEmpty()) {
29
res.append(stack.pop());
30
}
31
return res.reverse().toString();
32
}
33
}
Copied!

3. Time & Space Complexity

时间和空间复杂度都是O(n)