leetcode 20. 有效的括号【栈】

题目链接

https://leetcode-cn.com/problems/valid-parentheses/

代码

class Solution {
public:
    bool isValid(string str) {
        stack<int> s;
    int n = str.size();
    for (int i = 0;i<n; i++)
    {
        if(str[i]=='('||str[i]=='['||str[i]=='{')
            s.push(str[i]);
        else if(s.empty())
            return 0;
        else if((str[i]==')'&s.top()=='(')||(str[i]==']'&s.top()=='[')||(str[i]=='}'&s.top()=='{'))
            s.pop();
        else
            return 0;
    }    
    if(!s.empty())
        return 0;
    else
        return 1;
    }

};

注意:

用leetcode提交的C++代码,其中字符串s的长度使用:s.size()
用codeblocks编译:strlen(s)

原文地址:https://www.cnblogs.com/jiaxinwei/p/12748201.html