leetcode20_有效的括号

1、题目

 

 2、分析

  使用栈来实现这个结构,如果是左括号,则入栈,如果遇到对应的右括号,则左括号出栈,如果为空则再次入栈。

3、代码

  

class Solution {
public:
    bool isValid(string s) {
        stack<char> pre;
        unordered_map <char, int> dict = {{'{',1},{'[',2},{'(',3},{'}',4},{']',5},{')',6}};
        for(int i=0; i<s.size(); i++){
            if(i>0)
            {
                if(!pre.empty()){
                    if( dict[pre.top()]==dict[s[i]]-3) 
                        pre.pop();
                    else
                        pre.push(s[i]);
                }
                else{
                    pre.push(s[i]);
                }
            }
            else{
                pre.push(s[i]);
            }
        }
        return pre.empty();
    }
};

 

posted @ 2021-12-13 16:39  星光夜  阅读(24)  评论(0编辑  收藏  举报