Balanced Bracket

C. Recover an RBS

Given a sequence of (, ) and ?, check if there is a unique way to replace all the ? with either ( or ).  The given sequence is guranteed to have at least 1 balanced sequence. 

Key ideas: 

1. There will be N / 2 (,  N / 2 ), so replacing ? with ( greedily until we have N / 2 (, then replace the rest ? with ) always gives us a balanced sequence.

2. If there is any other valid sequence, there must exist at least one swap such that : S[L] == ? and it is changed from ( to ). S[R] == ? and it is changed from ) to (. Such a swap is going to cause the balance difference decrease by at least 2.

3. Let S[L] be the last ? we replaced with ( and S[R] be the first ? we replaced with ). If there is any other valid sequence, doing a swap of step 2 on L and R must still gives us a balanced sequence. This is true because any other swap changes is also going to cause a -2 diff change in the segment S[L, R]. So we can just do this swap, then verify if we still get a balanced sequence or not.

 

posted @ 2023-05-15 12:09  Review->Improve  阅读(30)  评论(0)    收藏  举报