Learner Level
Implement the isValidBracketPairString method that checks whether a bracket string has properly matched and ordered brackets.
The input contains a string brackets made of opening and closing parentheses. Your task is to check whether the parentheses are properly balanced.
A valid bracket pair string means every opening parenthesis ( has a matching closing parenthesis ), and a closing parenthesis must never appear before its matching opening parenthesis. For example, ()() and (()) are valid, but ())( is not.
Use a balance counter while scanning the string from left to right.
Increase the balance for every opening parenthesis and decrease it for every closing parenthesis. If the balance becomes negative at any point, a closing parenthesis appeared too early, so return false. At the end, the balance must be 0.
Pseudocode:
function isValidBracketPairString(brackets):
balance = 0
for each character ch in brackets:
if ch == '(':
balance++
else if ch == ')':
balance--
if balance < 0:
return false
return balance == 0