算法思路:

1.创建一个栈,用于存储左括号。

2.遍历表达式中的每个字符,如果是左括号,则入栈;如果是右括号,则将栈顶元素出栈。

3.如果当前字符不是括号,则继续遍历下一个字符。

4.如果栈为空,说明所有左括号都有相应的右括号与之匹配,返回 true;否则返回 false。

代码实现:

C++ 代码:

bool isMatching(string s) {
    stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '[' || c == '{') {
            st.push(c);
        } else if (c == ')') {
            if (st.empty() || st.top() != '(') {
                return false;
            }
            st.pop();
        } else if (c == ']') {
            if (st.empty() || st.top() != '[') {
                return false;
            }
            st.pop();
        } else if (c == '}') {
            if (st.empty() || st.top() != '{') {
                return false;
            }
            st.pop();
        }
    }
    return st.empty();
}

Python 代码:

def is_matching(s: str) -> bool:
    st = []
    for c in s:
        if c == '(' or c == '[' or c == '{':
            st.append(c)
        elif c == ')':
            if not st or st[-1] != '(':
                return False
            st.pop()
        elif c == ']':
            if not st or st[-1] != '[':
                return False
            st.pop()
        elif c == '}':
            if not st or st[-1] != '{':
                return False
            st.pop()
    return not st

时间复杂度:$O(n)$,其中 n 是表达式中字符的个数。

空间复杂度:$O(n)$,其中 n 是表达式中字符的个数,栈最多存储 n/2 个左括号。

本题实现求表达式中括号是否匹配。只需判断表达式中括号本题中只会出现三种括号分别是小括号中括号和大括号是否匹配表达式中可以有其他值也可没有。

原文地址: https://www.cveoy.top/t/topic/bjX1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录