Untitled
unknown
java
10 months ago
1.9 kB
6
Indexable
import java.util.*;
class Solution {
public String solution(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char ch : s.toCharArray()) {
if (ch == '$') {
if (!stack.isEmpty()) {
removeSmallest(stack);
}
} else {
stack.push(ch);
}
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.append(stack.pollLast()); // Retrieve characters in order
}
return result.toString();
}
private void removeSmallest(Deque<Character> stack) {
List<Character> temp = new ArrayList<>(stack);
char minChar = Collections.min(temp);
stack.removeLastOccurrence(minChar);
}
}
}
}
}
}
}
}
}
}Editor is loading...
Leave a Comment