【Leetcode】20.有效的括号C++(用map解决)

在这里插入图片描述
在这里插入图片描述

/*
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
*/

#include "iostream"

#include "string"

#include "stack"

#include "map"

using namespace std;

class Solution
{
public:
    bool isValid(string s)
    {
        stack<char> z;
        map<char, char> m;

        m['('] = ')';
        m['['] = ']';
        m['{'] = '}';

        for (char c : s)
        {
            if (c == '(' || c == '[' || c == '{')
            {
                z.push(c);
            }
            else
            {
                if(z.empty())
                {
                    return false;
                }
                else if (m[z.top()] == c)
                {
                    z.pop();
                }
                else
                {
                    return false;
                }
            }
        }
        if (z.empty())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

int main(int argc, char const *argv[])
{
    string s;
    cin >> s;

    Solution so;
    cout << so.isValid(s) << endl;

    return 0;
}
发布了103 篇原创文章 · 获赞 128 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104091367