class Solution {
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<char> st;
for(int i=0;i<s.length();i++){
if(s[i]=='(')
st.push(s[i]);
else if(s[i]==')'){
if(st.empty()||st.top()!='(')
return false;
st.pop();
}
else if(s[i]=='{')
st.push(s[i]);
else if(s[i]=='}'){
if(st.empty()||st.top()!='{')
return false;
st.pop();
}
else if(s[i]=='[')
st.push(s[i]);
else if(s[i]==']'){
if(st.empty()||st.top()!='[')
return false;
st.pop();
}
else
return false;
}
return st.empty();
}
};
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<char> st;
for(int i=0;i<s.length();i++){
if(s[i]=='(')
st.push(s[i]);
else if(s[i]==')'){
if(st.empty()||st.top()!='(')
return false;
st.pop();
}
else if(s[i]=='{')
st.push(s[i]);
else if(s[i]=='}'){
if(st.empty()||st.top()!='{')
return false;
st.pop();
}
else if(s[i]=='[')
st.push(s[i]);
else if(s[i]==']'){
if(st.empty()||st.top()!='[')
return false;
st.pop();
}
else
return false;
}
return st.empty();
}
};
本文介绍了一个使用C++实现的括号匹配验证算法。该算法通过栈来检查输入字符串中的括号(包括圆括号、方括号和花括号)是否正确配对。主要步骤包括遍历字符串并利用栈来跟踪左括号,当遇到右括号时检查栈顶的左括号是否匹配。
232

被折叠的 条评论
为什么被折叠?



