题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
#include <iterator>
#include <stack>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return bool布尔型
*/
bool isValid(string s) {
// write code here
stack<char> st;//创建栈
for(char sc:s)//循环语法遍历字符串 s{
//若遇到左括号入栈
if(sc=='{'||sc=='['||sc=='(') {
st.push(sc);
}
//若以上if不成立,判断之前是否有左括号入栈,若没有表名s是右括号开头的字符串返回false
else if(st.empty()){
return false;
}
//判断遍历的字符串是否为右括号,并且栈顶元素是否为相匹配的左括号不是则条件成立返回false
else if(sc=='}'&&st.top()!='{'||sc==']'&&st.top()!='['||sc==')'&&st.top()!='(') {
return false;
}else// 弹出栈顶元素
st.pop();
}
//遍历结束如果栈为空返回ture否则为false
return st.empty();
}
};
查看15道真题和解析

