-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay26
34 lines (27 loc) · 897 Bytes
/
Day26
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
class Solution {
public String removeDuplicateLetters(String s) {
int n=s.length();
int lastOcurrence[]=new int[26];
for(int i=0;i<n;i++)
lastOcurrence[s.charAt(i)-'a']=i;
boolean visited[]=new boolean[26];
Stack<Integer>stack=new Stack<>();
for(int i=0;i<n;i++){
int currChar=s.charAt(i)-'a';
if(visited[currChar])
continue;
while(!stack.isEmpty() && stack.peek()>currChar
&& i<lastOcurrence[stack.peek()])
{
visited[stack.pop()]=false;
}
stack.push(currChar);
visited[currChar]=true;
}
StringBuilder str=new StringBuilder();
while(!stack.isEmpty()){
str.append((char)( stack.pop()+'a' ));
}
return str.reverse().toString();
}
}