Stack
Last updated
Was this helpful?
Last updated
Was this helpful?
Stack class in Java uses synchronized methods since it is a subclass of Vector.
A more complete and consistent set of LIFO stack operations is provided by the interface and its implementations, which should be used in preference to this class. For example:
Stack + Set solution, 2 pass
first pass
Stack to store index of pendingLeft
Set to store index of unpaired right bracket
move element from stack to set
then second pass:
if set.contains(curIdx), then skip it/don't append it
O(N) Time , O(N) space
这题还有O(1) space solution, 不用Stack, Set
需要记录两个变量,pendingRight和unpairedLeft
先scan 一遍记录pendingRight cnt
然后再scan, 每次遇到一个left bracket, 则unpairedLeft++
比较tricky, 感觉面试时应该不要求优化到O(1)吧