开发者

Nice way to store the number of elements between braces?

开发者 https://www.devze.com 2023-01-21 20:10 出处:网络
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

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.

  • 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消