首页 > 其他 > 详细

[LeetCode] Valid Parentheses

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

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

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

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!