码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Valid Parentheses

时间:2014-11-15 12:50:41      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   os   sp   for   div   on   

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.

 

这题虽然简单但是我也没有一次就AC,问题在于取top和pop的时候忘了做异常判断,切记切记。

此外找conterpart也许是个比较头疼的问题,但是用hashmap就方便多了

map<char, char> conterpart;

bool isValid(string s) {
    conterpart[(] = );
    conterpart[[] = ];
    conterpart[{] = };
    
    if (s.empty()) return true;
    stack<char> st;
    for (int i = 0; i < s.size(); i++) {
        char c = s.at(i);
        if (c == ( || c == [ || c == {) {
            st.push(c);
        }
        else if (c == ) || c == ] || c == }){
            if (st.empty()) return false;
            if ( conterpart[st.top()] != c) {
                return false;
            }
            else {
                st.pop();
            }
        }
    }
    
    if (st.empty()) {
        return true;
    }
    return false;
}

 

[LeetCode] Valid Parentheses

标签:style   blog   color   ar   os   sp   for   div   on   

原文地址:http://www.cnblogs.com/agentgamer/p/4099123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!