Determining Validity of Strings with Brackets

This technical problem deals with determining whether or not a given string consisting of only brackets is valid. A string is considered valid if the open brackets are closed by the same type of brackets in the correct order. An empty string is also considered valid.

Problem

Given a string consisting of only '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example:
Input: "()"
Output: true
Input: "()[]{}"
Output: true
Input: "(]"
Output: false
Input: "([)]"
Output: false
Input: "{[]}"
Output: true

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
# Solution:
# The solution is to use a stack to keep track of the order of the brackets.
# If the current character is a closing bracket, then the previous character in the stack must be the corresponding opening bracket, otherwise the string is not valid.
# The stack will be empty at the end if the string is valid.

def isValid(s):
    stack = []
    dict = {"]":"[", "}":"{", ")":"("}
    for char in s:
        if char in dict.values():
            stack.append(char)
        elif char in dict.keys():
            if stack == [] or dict[char] != stack.pop():
                return False
        else:
            return False
    return stack == []

print(isValid("()"))
print(isValid("()[]{}"))
print(isValid("(]"))
print(isValid("([)]"))
print(isValid("{[]}"))

A.I. Evaluation of the Solution

The candidate's solution is correct and uses a stack to keep track of the order of the brackets. The solution is also complete, with tests for all the different cases.

Evaluated at: 2022-12-03 08:15:33