Matching pairs of brackets in a string is a classic problem often encountered in programming interviews. The goal is to determine if the string has well-formed and matching brackets.
Consider the following examples:
"[]" �� This is well-formed."{[()]}" �� This is well-formed."{[(])}" �� This is not well-formed."{" �� This is not well-formed.A stack is an ideal data structure for this problem. We'll iterate through the string and:
def is_matched(expression): stack = [] bracket_map = {')': '(', '}': '{', ']': '['} for char in expression: if char in bracket_map.values(): # If character is an opening bracket stack.append(char) elif char in bracket_map.keys(): # If character is a closing bracket if stack == [] or bracket_map[char] != stack.pop(): return False else: return False # Invalid character return stack == [] # Test cases print(is_matched("{[()]}")) # True print(is_matched("{[(])}")) # False print(is_matched("{")) # False For the string "{[()]}":
{ is pushed onto the stack.[ is pushed onto the stack.( is pushed onto the stack.) matches with the top of the stack ((), so ( is popped.] matches with the top of the stack ([), so [ is popped.} matches with the top of the stack ({), so { is popped.For the string "{[(])}":
{ is pushed onto the stack.[ is pushed onto the stack.( is pushed onto the stack.] does not match with the top of the stack ((), so we know it's not well-formed.Text Editors/IDEs: They often highlight mismatched brackets in your code to help you spot errors.
Compilers: They check for well-formed brackets to validate the syntax of code.
Performance: This algorithm runs in linear time, O(n), since we iterate through the string once and perform constant-time operations for each character.
Extensions: The basic concept can be extended to other matching pairs, not just typical brackets. For instance, matching HTML or XML tags.
Empty String: An empty string can be considered as well-formed.
Using a stack is a straightforward and effective approach for matching pairs of brackets. This method ensures that we not only have a matching closing bracket for every opening bracket but also that they are in the correct order.
wifi capacity-planning keyword unc flutter-packages trailing odata messaging real-time-data tcpdf