@requires_authorization
@author johnsondu
@create_time 2015.7.13 11:03
@url [valid parentheses](https://leetcode.com/problems/valid-parentheses/)
/*****************
* 类别: 栈模拟判断
* 时间复杂度: O(n)
* 空间复杂度: O(n)
****************/
class Solution {
public:
bool isValid(string s) {
stack<char> st;
int len = s.size();
for(int i = 0; i < len; i ++){
if(s[i] == ']' || s[i] == '}' || s[i] == ')'){
if(st.empty()){
return false;
}
}
else{
st.push(s[i]);
continue;
}
if(s[i] == ']'){
char ch = st.top();
st.pop();
if(ch != '[') return false;
continue;
}
if(s[i] == ')'){
char ch = st.top();
st.pop();
if(ch != '(') return false;
continue;
}
if(s[i] == '}'){
char ch = st.top();
st.pop();
if(ch != '{') return false;
continue;
}
}
if(st.empty()) return true;
else return false;
}
};
【leetcode】20. Valid Parentheses
最新推荐文章于 2024-02-05 23:11:57 发布
本文介绍了一种使用栈数据结构来验证括号是否正确配对的方法。该算法的时间复杂度为O(n),空间复杂度也为O(n)。通过遍历输入字符串并利用栈进行辅助判断,可以有效地检查方括号([])、圆括号(())和花括号({}
973

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



