[LeetCode]Valid Parentheses

来源:互联网 发布:软件测试28原则 编辑:程序博客网 时间:2024/06/06 05:05

这里写图片描述

class Solution {public:    bool isValid(string s) {        stack<char> sta;        map<char,int> m ={{'(',-1}, {'{',-2}, {'[',-3}, {')',1} ,{'}',2},{']',3}};        if(s.size()<=1) return false;        for(int i=0;i<s.size();++i){            if(s[i]=='('||s[i]=='{'||s[i]=='[')                sta.push(s[i]);            else{                if(sta.empty())                    return false;                else{                    char c = sta.top();                    if(m[c]+m[s[i]]==0)                        sta.pop();                    else                        return false;                }            }        }        if(sta.empty())            return true;        else            return false;    }};
#include <string>#include <stack>using std::string; using std::stack; class Solution {public:    bool isValid(string s) {        stack<char> stk;        for (auto c : s)            if (!stk.empty() && ((c == ')' && stk.top() == '(') || (c == '}' && stk.top() == '{') || (c == ']' && stk.top() == '['))) stk.pop();            else stk.push(c);        return stk.empty();    }};
0 0