zoukankan      html  css  js  c++  java
  • Leetcode: 20. Valid Parentheses

    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.

    思路

    • 左括号都入栈
    • 遇到右括号时,判断栈顶和它是否匹配,不匹配,直接返回,匹配,出栈

    代码

    class Solution {
    public:
        bool isValid(string s) {
            int len = s.size();
            if(len == 0) return false;
            
            stack<char> Stack;
            for(int i = 0; i < len; ++i){
                if(s[i] == '(' || s[i] == '{' || s[i] == '[')
                    Stack.push(s[i]);
                else if(s[i] == ')'){
                    if(Stack.empty() || Stack.top() != '(')
                        return false;
                    else Stack.pop();
                }
                else if(s[i] == '}'){
                    if(Stack.empty() || Stack.top() != '{')
                        return false;
                    else Stack.pop();
                }
                else if(s[i] == ']'){
                    if(Stack.empty() || Stack.top() != '[')
                        return false;
                    else Stack.pop();
                }
                else return false;
            }
            
            return Stack.empty();
            
        }
    };
    
  • 相关阅读:
    python_深浅拷贝
    Python_三级菜单
    python 字符串
    python_字典
    初识Python
    C# ADO.NET面向对象想法
    C# ADO.NET
    C# ADO.NET 面向对象
    C# 数据库连接增删改查
    C# 面向对象多态的抽象性&接口 object&is as类型转换运算符
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6822296.html
Copyright © 2011-2022 走看看