Problem · Stack
Stack Command Output
Learn this problemProblem statement
Process a command string commands using an initially empty stack. Return the values removed by pop commands, in the order they are removed.
U valuepushes the signed integervalueonto the stack.Oremoves the top value and appends it to the output.Xends the command string. Values still on the stack are not output.
For this exercise, assume the input is valid: tokens are separated by one or more spaces, tabs, or newlines, optional whitespace may surround the string, exactly one X is the final token, and every O has a value available to pop. Integers use ordinary decimal notation with an optional leading minus sign.
Function
stackOutput(commands: String) → int[]Examples
Example 1
commands = "U 3 U -3 O O X"return = [-3,3]Push 3, then -3. The first pop removes -3; the second removes 3.
Example 2
commands = "U 8 O U 4 U 9 O X"return = [8,9]The pops remove 8 and then 9. The remaining 4 is not output when X ends processing.
Constraints
1 <= commands.length <= 10^5.- There are at most
10^4commands, includingX. - Every pushed value is between
-10^9and10^9, inclusive. - The command sequence satisfies the validity rules in the statement.