首页 > 代码库 > [LeetCode] Valid Parentheses

[LeetCode] Valid Parentheses

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