-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay41_LeetCode316.java
39 lines (29 loc) · 1001 Bytes
/
Day41_LeetCode316.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
class Solution {
public String removeDuplicateLetters(String s) {
int[] lastIndex = new int[26];
for(int i=0;i<s.length();i++){
char ch = s.charAt(i);
int idx = (int)(ch-'a');
lastIndex[idx]= i ;
}
boolean[] present = new boolean[26];
Stack<Character> st = new Stack<>();
for(int i=0;i<s.length();i++){
char ch = s.charAt(i);
int idx = (int)(ch-'a');
if(present[idx]==false){
while(st.size()>0 && st.peek()>ch && lastIndex[(int)(st.peek()-'a')]>i){
present[(int)(st.peek()-'a')]=false;
st.pop();
}
st.push(ch);
present[idx]=true ;
}
}
StringBuilder sb = new StringBuilder("");
while(st.size()>0){
sb.append(st.pop());
}
return sb.reverse().toString();
}
}