LeetCode算法学习(8)

题目描述

Valid Parentheses
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

题目大意

括号匹配。

思路分析

简单的栈的应用。

关键代码

    bool match(char a, char b) {
        if (a == '(') return b == ')';
        if (a == '[') return b == ']';
        if (a == '{') return b == '}';
        return false;
    }

    bool isValid(string s) {
        stack<char> stack1;
        int n = s.length();
        for (int i = 0; i < n; i++) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
                stack1.push(s[i]);
            } else if (stack1.empty()) {
                return false;
            } else {
                if (match(stack1.top(), s[i])) {
                    stack1.pop();
                } else {
                    return false;
                }
            }
        }
        if (stack1.empty()) {
            return true;
        } else {
            return false;
        }
    }

总结

当复习栈吧。

猜你喜欢

转载自blog.csdn.net/L_Realoo/article/details/85270262
今日推荐