题解 | #括号序列#
括号序列
http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
入栈要匹配的右半括号,再检查
stack<char> st; for(int i=0; i<s.size(); ++i){ if(s[i] == '{') st.push('}'); else if(s[i] == '(') st.push(')'); else if(s[i] == '[') st.push(']'); else if(st.empty()) return false; else if(s[i] != st.top()) return false; else st.pop(); } return st.empty();
模拟括号匹配的过程
map<char, char> m; m['('] = ')'; m['{'] = '}'; m['['] = ']'; stack<char> st; for(int i=0; i<s.size(); ++i){ if(s[i] == '{' || s[i] == '(' || s[i] == '[') st.push(s[i]); else if(st.empty()) return false; else if(s[i] == m[st.top()]) st.pop(); } return st.empty();