zoukankan      html  css  js  c++  java
  • Valid Parentheses

    题目:

    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.

    思路:

    遇到 “(”  “{”  “[”,进入堆栈;

    如果不是,查看堆栈中是否为空,为空,false。

                        不为空,查看顶端字符与当前字符是否配对,并出栈。

    代码:

    class Solution {
    public:
        bool isValid(string s) {
            if(s.empty())
                return false;
            int len=s.length();
            stack<char>stk;
            
            for(int i=0;i<len;i++){
                if(s[i]=='['||s[i]=='{'||s[i]=='('){
                    stk.push(s[i]);
                }else{
                    if(stk.empty()){
                        return false;
                    }else if(stk.top()=='{'&&'}'==s[i]){
                        stk.pop();
                    }else if(stk.top()=='['&&']'==s[i]){
                        stk.pop();
                    }else if(stk.top()=='('&&')'==s[i]){
                        stk.pop();
                    }else
                        return false;
                }
            }
            return stk.empty();//假如出现“()”,没有这句话,就会没有数值输出
        }
    };


  • 相关阅读:
    内存对齐
    C++中构造函数
    计算机视觉领域的大牛主页
    各种银行卡的收费情况
    常识
    毕业生必须知道
    计算机视觉领域资料
    人际关系
    生活常识
    可使用在项目的web gantt甘特图有哪些?
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519821.html
Copyright © 2011-2022 走看看