2020-11-15(有效的括号)

2020-11-15  本文已影响0人  hannah1123

class Solution {                                       //整体思路:1)维护一个字符数字s和一个char类型的stack;

public:                                                                          2)遍历s,对其中的所有的左括号进行push到stack中,

    bool isValid(string s) {                                                  对s中所有类型的右括号,检查stack 中的最近有匹配;

        int n = s.length();                                       类型,有就把st出栈pop,否则返回false,算法结束;(一个类型一个                                                                                                      类型的检查)

        if(n == 0)

            return true;

        stack<char> st;

        for(int i = 0; i < n; i++)

        {

            if(s[i] == '(' || s[i] == '[' || s[i] =='{')

                st.push(s[i]);

            if(s[i] == ')')

            {

                if(!st.empty() && st.top() == '(')

                    st.pop();

                else

                    return false;

            }

            if(s[i] == ']')

            {

                if(!st.empty() && st.top() == '[')

                    st.pop();

                else

                    return false;

            }

            if(s[i] == '}')

            {

                if(!st.empty() && st.top() == '{')

                    st.pop();

                else

                    return false;

            }

        }

        if(st.empty())

            return true;

        return false;

    }

};

上一篇 下一篇

猜你喜欢

热点阅读