[Leetcode] Valid Parentheses

Valid Parentheses 题解

题目来源:https://leetcode.com/problems/


Description

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Solution


class Solution {
public:
    bool isValid(string s) {
        stack<char> pstack;
        for (auto c : s) {
            if (c == '(' || c == '[' || c == '{') {
                pstack.push(c);
            } else {
                if (pstack.empty())
                    return false;
                char l = pstack.top();
                pstack.pop();
                if ((l == '(' && c != ')') ||
                    (l == '[' && c != ']') ||
                    (l == '{' && c != '}'))
                    return false;
            }
        }
        return pstack.empty();
    }
};


解题描述

这道题是经典的括号匹配问题。主要的思想是利用栈的想法(也是编译中用到的算法),当是左括号的时候就入栈,是右括号的时候就出栈,出栈的时候左右括号看是否匹配即可。

原文地址:https://www.cnblogs.com/yanhewu/p/8390865.html