Stack to the Rescue
The easiest way to accomplish what we want is with a stack
data structure, as its push()
and pop()
methods model the pair-wise opposing symbols in an efficient manner (the push
/pop
operations for most stack implementations is O(1)
).
With a simple stack in place, we can start by iterating through the given string.
At each step, look for any opening/left-side symbol and push it onto the stack
. Here's a sample snippet of what that looks like.
xxxxxxxxxx
10
const stack = [];
const str = "[{()}]";
for (let i = 0; i < str.length; i++) {
if (str[i] === "(" || str[i] === "[" || str[i] === "{") {
stack.push(str[i]);
}
}
console.log(stack);
OUTPUT
Results will appear here.