zoukankan      html  css  js  c++  java
  • [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();
        }
    };
    
    

    解题描述

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

  • 相关阅读:
    代理模式
    适配器模式
    原型模式
    创建者模式
    装饰模式
    web总结
    4.14
    4.14
    POJ2385
    POJ2229
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8390865.html
Copyright © 2011-2022 走看看