-
Notifications
You must be signed in to change notification settings - Fork 2
/
RemoveDuplicateLetters.java
66 lines (55 loc) · 1.9 KB
/
RemoveDuplicateLetters.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package Leetcode;
import java.util.*;
/**
* @author kalpak
*
* 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.
*
*/
public class RemoveDuplicateLetters {
public static String removeDuplicateLetters(String s) {
Map<Character, Integer> lastOccurence = new HashMap<>();
Set<Character> isVisited = new HashSet<>();
Deque<Character> stack = new ArrayDeque<>(); // answer stack
StringBuilder result = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
lastOccurence.put(s.charAt(i) , i);
}
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(isVisited.contains(c)) // if character is already present in stack, dont bother
continue;
//if current character is smaller than last character in stack which occurs later in the string again
//it can be removed and added later e.g stack = bc remaining string abc then a can pop b and then c
while(!stack.isEmpty() && c < stack.peek() && lastOccurence.get(stack.peek()) > i) {
isVisited.remove(stack.pop());
}
stack.push(c); //add current character and mark it as visited
isVisited.add(c);
}
//pop character from stack and build answer string from back
while(!stack.isEmpty()){
result.insert(0, stack.pop());
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(removeDuplicateLetters("bcabc"));
}
}