臭道人

1.28

栈的应用,简单配对,map运用

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

做题收获:①map.count()用法

②stack.top(),stack.push(ch),stack.pop();区别于map[ch]不是map(ch);

③简单配对的思路

练习题:

https://leetcode-cn.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/

#include<iostream>
#include<unordered_map>
#include<stack>
using namespace std;
bool is(string s)
{
    int n=s.length();
    if(n&1){return false;}
    unordered_map<char,char>pairs
        {  {']','['},  {')','('},  {'}','{'} };
    stack<char>stk;
    for(char ch:s)
    {
        if(pairs.count(ch))
            {
            if(stk.empty()||stk.top()!=pairs[ch])
            {return false;}
            stk.pop();
            }
        else stk.push(ch);
    }
    return stk.empty();
}
int main()
{
    string ch;
    cin>>ch;
    cout<<is(ch);
}

 

posted on 2021-01-28 20:46  臭总  阅读(71)  评论(0编辑  收藏  举报

导航