leetcode 20 Valid Parentheses 有效的括号

描述:

给定一些列括号,判断其有效性,即左括号有对应的有括号,括号种类只为小,中,大括号。

解决:

用栈。

bool isValid(string s) {        
    stack<char> st;
    for (auto i : s) {
        if (i == '(' || i == '[' || i == '{') {
            st.push(i);
            continue;
        } else {
            if (st.empty())
                return false;
            char c = st.top();
            if (i == ')' && c != '(' ||
                i == ']' && c != '[' ||
                i == '}' && c != '{')
                return false;
            st.pop();
        }
    }
    if (st.empty())
        return true;
    return false;
}

 

posted on 2018-01-22 10:03  willaty  阅读(97)  评论(0编辑  收藏  举报

导航