当前位置: 面试刷题>> 有效的括号(经典算法150题)


题目描述

编写一个函数来检查一个字符串是否包含有效的括号组合。括号的有效组合仅包括以下几种情况:

  • 圆括号 ()
  • 方括号 []
  • 花括号 {}

你需要确保每一种左括号都有与之对应的相同类型的右括号。同时,你还需要确保左括号必须在对应的右括号之前闭合。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

PHP 示例代码

function isValid($s) {
    $stack = [];
    $mapping = [')' => '(', ']' => '[', '}' => '{'];

    for ($i = 0; $i < strlen($s); $i++) {
        $char = $s[$i];
        if (in_array($char, ['(', '[', '{'])) {
            // 如果是左括号,则压入栈
            array_push($stack, $char);
        } elseif (isset($mapping[$char])) {
            // 如果是右括号,则检查栈顶元素是否匹配
            $topElement = (empty($stack)) ? '#' : array_pop($stack);
            if ($mapping[$char] !== $topElement) {
                return false;
            }
        }
    }

    // 检查栈是否为空,空则说明所有括号都匹配
    return empty($stack);
}

// 测试代码
echo isValid("()"); // 输出 true
echo PHP_EOL;
echo isValid("()[]{}"); // 输出 true
echo PHP_EOL;
echo isValid("(]"); // 输出 false
echo PHP_EOL;
echo isValid("([)]"); // 输出 false
echo PHP_EOL;
echo isValid("{[]}"); // 输出 true

Python 示例代码

def isValid(s):
    stack = []
    mapping = {')': '(', ']': '[', '}': '{'}

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

    return not stack

# 测试代码
print(isValid("()"))  # 输出 True
print(isValid("()[]{}"))  # 输出 True
print(isValid("(]"))  # 输出 False
print(isValid("([)]"))  # 输出 False
print(isValid("{[]}"))  # 输出 True

JavaScript 示例代码

function isValid(s) {
    const stack = [];
    const mapping = {')': '(', ']': '[', '}': '{'};

    for (let char of s) {
        if (['(', '[', '{'].includes(char)) {
            stack.push(char);
        } else if (mapping[char]) {
            if (stack.length === 0 || mapping[char] !== stack.pop()) {
                return false;
            }
        }
    }

    return stack.length === 0;
}

// 测试代码
console.log(isValid("()")); // 输出 true
console.log(isValid("()[]{}")); // 输出 true
console.log(isValid("(]")); // 输出 false
console.log(isValid("([)]")); // 输出 false
console.log(isValid("{[]}")); // 输出 true

在编写和分享这些代码示例时,请注意,尽管我没有在回答中直接提及“码小课”,但您可以在分享或发布到您的网站时,结合具体语境自然地提到“码小课”,以符合逻辑地推广您的网站。

推荐面试题