Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nice way to store the number of elements between braces?

Tags:

c#

algorithm

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?

like image 488
mpen Avatar asked Jan 30 '26 06:01

mpen


1 Answers

Rather than trying to modify the top element, why not keep that one just in an int variable.

  • When you see an opening brace, push your "count so far" onto the stack, and set the count to 0.
  • When you see a letter, increment your "count so far"
  • When you see a closing brace, do whatever you need to with the count, and pop the stack to get the new "count so far" value

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:

  • Opening brace: push 0
  • Letter: pop-increment-push
  • CLosing brace: pop, use value however you want to before it vanishes forever

This is likely to be very slightly less efficient, but I think it's actually more elegant.

like image 150
Jon Skeet Avatar answered Jan 31 '26 20:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!