题解 | #栈——有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
//如果是( { [ 就压入相反的括号 如果遇到的符号和栈顶元素相同 弹出栈顶 元素 否则入栈。最后判断站是否为空。如果合法栈应该是空的
class Solution {
public:
/**
*
* @param s string字符串
* @return bool布尔型
*/
bool isValid(string s) {
// write code here
stack<char> s1;
for(int i=0;i<s.length();i++){
if(s[i] == '(') s1.push(')');
else if(s[i] == '[') s1.push(']');
else if(s[i] =='{') s1.push('}');
else if(!s1.empty() &&s1.top() == s[i]) s1.pop();
else s1.push(s[i]);
}
return s1.empty();
}
};

格力公司福利 246人发布