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.
题目比较简单,一看就知道对栈的考查。不多说,上代码。
bool isValid(string s) { if(s.empty()) return true; if(s.size()%2 == 1) return false; stack<char> st; for(int i =0;i<s.size();i++) { char tmp=s[i]; if(tmp==‘(‘ || tmp==‘[‘ || tmp==‘{‘ ) { st.push(tmp); } else { if(st.empty()) return false; if( (tmp==‘)‘&&st.top()==‘(‘) || (tmp==‘]‘&&st.top()==‘[‘) || (tmp==‘}‘&&st.top()==‘{‘) ) st.pop(); else return false; } if(st.empty()) return true; } }
再看别人写的,利用自动变量,鲁棒性比较好,代码比较精炼。
bool isValid(string s) { string left = "([{", right = ")]}"; stack<char> stk; for (auto c : s) { if (left.find(c) != string::npos) { stk.push(c); } else { if (stk.empty() || stk.top() != left[right.find(c)]) return false; else stk.pop(); } } return stk.empty(); }
时间: 2024-10-13 00:18:06