解法一:使用栈 思路:

  1. 创建一个空栈。
  2. 遍历输入字符串的每个字符。
  • 如果字符是左括号('(', '{', '['),则将其推入栈中。
  • 如果字符是右括号(')', '}', ']'),则检查栈是否为空。
  • 如果栈为空,则返回False,因为没有与之匹配的左括号。
  • 如果栈不为空,则弹出栈顶元素,并判断它与当前右括号是否匹配。如果不匹配,则返回False。
  1. 遍历完所有字符后,检查栈是否为空。如果为空,则返回True;否则,返回False。

示例代码如下:

def isValid(s):
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}
    for char in s:
        if char in mapping:
            if not stack or stack.pop() != mapping[char]:
                return False
        else:
            stack.append(char)
    return not stack

# 测试示例
print(isValid("()"))  # True
print(isValid("()[]{}"))  # True
print(isValid("(]"))  # False
print(isValid("([)]"))  # False
print(isValid("{[]}"))  # True

解法二:使用计数器 思路:

  1. 使用三个变量count1count2count3分别表示左括号({[的数量,初始值为0。
  2. 遍历输入字符串的每个字符。
  • 如果字符是左括号,则相应的计数器加1。
  • 如果字符是右括号,则相应的计数器减1。
  • 如果任何计数器的值小于0,则返回False,因为出现了右括号比左括号多的情况。
  1. 遍历完所有字符后,检查三个计数器的值是否都为0。如果是,则返回True;否则,返回False。

示例代码如下:

def isValid(s):
    count1 = count2 = count3 = 0
    for char in s:
        if char == '(':
            count1 += 1
        elif char == ')':
            count1 -= 1
        elif char == '{':
            count2 += 1
        elif char == '}':
            count2 -= 1
        elif char == '[':
            count3 += 1
        elif char == ']':
            count3 -= 1
        if count1 < 0 or count2 < 0 or count3 < 0:
            return False
    return count1 == count2 == count3 == 0

# 测试示例
print(isValid("()"))  # True
print(isValid("()[]{}"))  # True
print(isValid("(]"))  # False
print(isValid("([)]"))  # False
print(isValid("{[]}"))  # True