[Algorithms] LeetCode 20. 有效的括号
Categories Algorithms StackAndQueue
Tags
来源:代码随想录
栈模拟
注意最后判断空栈。
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
st.push(s[i]);
continue;
}
if (st.empty()) {
return false;
}
if (s[i] == '}') {
if (st.top() == '{') {
st.pop();
} else {
return false;
}
}
if (s[i] == ']') {
if (st.top() == '[') {
st.pop();
} else {
return false;
}
}
if (s[i] == ')') {
if (st.top() == '(') {
st.pop();
} else {
return false;
}
}
}
if (!st.empty()) {
return false;
}
return true;
}
};
Page views: Loading... · Visitors: Loading...
Except where otherwise noted, original content on this site is dedicated to the public domain under CC0 1.0.
Powered by Hexo & Theme mdsuper
沪ICP备2026040813号