Skip to main content

Parenthesis Problems

checking Parenthesis Validity

caution
  • starting the balance with 0
  • for every ( ++balance
  • for every ) --balance
  • To Note here: whenever my balance has more ) than (, then I would have --balance more times, Hence, the balance < 0, thus false
  • Also to note at the very end I should get equal no. of ++balance & --balance, Hence MUST have balance == 0 else false
int balance = 0;
for (auto &el : s)
{
if (el == '(')
++balance;
else // (el == ')')
--balance;

if (balance < 0)
return false;
}
return (balance == 0);