File tree Expand file tree Collapse file tree 1 file changed +22
-24
lines changed Expand file tree Collapse file tree 1 file changed +22
-24
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public String removeDuplicateLetters (String s ) {
3
- int [] counter = new int [26 ];
4
- for (char c : s .toCharArray ()) {
5
- counter [c - 'a' ]++;
2
+ public String removeDuplicateLetters (String s ) {
3
+ Map <Character , Integer > lastIndexMap = new HashMap <>();
4
+ for (int i = 0 ; i < s .length (); i ++) {
5
+ lastIndexMap .put (s .charAt (i ), i );
6
+ }
7
+ Stack <Character > stack = new Stack <>();
8
+ Set <Character > visited = new HashSet <>();
9
+ for (int i = 0 ; i < s .length (); i ++) {
10
+ char c = s .charAt (i );
11
+ if (!visited .contains (c )) {
12
+ while (!stack .isEmpty () && c < stack .peek () && lastIndexMap .get (stack .peek ()) > i ) {
13
+ visited .remove (stack .pop ());
14
+ }
15
+ visited .add (c );
16
+ stack .push (c );
17
+ }
18
+ }
19
+ StringBuilder sb = new StringBuilder ();
20
+ for (Character c : stack ) {
21
+ sb .append (c );
22
+ }
23
+ return sb .toString ();
6
24
}
7
- Stack <Integer > stack = new Stack <>();
8
- boolean [] visited = new boolean [26 ];
9
- for (char c : s .toCharArray ()) {
10
- int idx = c - 'a' ;
11
- counter [idx ]--;
12
- if (visited [idx ]) {
13
- continue ;
14
- }
15
- while (!stack .isEmpty () && stack .peek () > idx && counter [stack .peek ()] > 0 ) {
16
- visited [stack .pop ()] = false ;
17
- }
18
- stack .add (idx );
19
- visited [idx ] = true ;
20
- }
21
- StringBuilder sb = new StringBuilder ();
22
- while (!stack .isEmpty ()) {
23
- sb .append ((char ) (stack .pop () + 'a' ));
24
- }
25
- return sb .reverse ().toString ();
26
- }
27
25
}
You can’t perform that action at this time.
0 commit comments