-
Notifications
You must be signed in to change notification settings - Fork 7
/
Main.java
30 lines (26 loc) · 842 Bytes
/
Main.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
package com.company;
import java.util.HashSet;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
String s = "abacb";
System.out.println(removeDuplicateLetters(s));
}
public static String removeDuplicateLetters(String s) {
int[] freq = new int[26];
for (Character c : s.toCharArray())
freq[c - 'a']++;
Stack<Character> stack = new Stack<>();
for (Character c : s.toCharArray()) {
freq[c - 'a']--;
if (stack.contains(c)) continue;
while (!stack.isEmpty() && freq[stack.peek() - 'a'] > 0 && c < stack.peek())
stack.pop();
stack.push(c);
}
String res = "";
while (!stack.isEmpty())
res = stack.pop() + res;
return res;
}
}