[leetcode]20. 有效的括号

在这里插入图片描述

class Solution {
public:
    bool isValid(string s) {
        stack<char>stk;
        map<char,char>hash;
        hash[')'] = '(';
        hash[']'] = '[';
        hash['}'] = '{';              
        for(int i = 0; i < s.size(); i++)
        {
            if(s[i] == '(' || s[i] == '[' || s[i] == '{')
            {
                stk.push(s[i]);
            }
            else if(!stk.empty())
            {
                char ch = stk.top();
                if(ch == hash[s[i]])
                {
                    stk.pop();
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        return stk.empty();
    }
};
发布了179 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40691051/article/details/104310902
今日推荐