“(” “{” “【”的判断

来源:互联网 发布:知金教育学历是真的吗 编辑:程序博客网 时间:2024/06/06 07:30

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

利用一个栈来保存前括号,然后有后括号来时弹出栈顶来判断

class Solution {public:    bool isValid(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        stack<char> st;                for(int i = 0; i < s.size(); i++)            if (s[i] == ')' || s[i] == ']' || s[i] == '}')            {                if (st.empty())                    return false;                else                {                    char c = st.top();                    st.pop();                    if ((c == '(' && s[i] != ')') || (c == '[' && s[i] != ']') || (c == '{' && s[i] != '}'))                        return false;                }            }            else                st.push(s[i]);                        return st.empty();    }};


0 0
原创粉丝点击