Given an input like
a { b c d { e f } g }
I want to parse it one token at at time (letter or brace). When I hit the first closing brace } I need to know how many elements there were since the last opening brace (e and f = 2). And then when I hit the one after that, I need 4 (b,c,d,g).
Grabbing the tokens 1 by 1 is easy, but... I don't know how to count them. I was thinking about Stack<int> but I can't modify the top element to increment it?
Rather than trying to modify the top element, why not keep that one just in an int variable.
EDIT: If you wanted to keep all the state in the stack itself, you can always think of the top element as a variable, which is changed by performing pop-increment-push. At that point, the operations are:
This is likely to be very slightly less efficient, but I think it's actually more elegant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With