From : https://leetcode.com/problems/valid-parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are
all valid but "(]" and "([)]" are
not.
class Solution {
public:
bool isValid(string s) {
stack<char> box;
int len = s.size();
char cur;
for(int i=0; i<len; i++) {
cur = s[i];
if(cur=='(' || cur=='[' || cur=='{') box.push(cur);
else if(cur==')' || cur==']' || cur=='}') {
if(box.empty()) return false;
char pre = box.top();
switch(cur) {
case ')' : {
if(pre == '(') box.pop();
else return false;
break;
}
case ']' : {
if(pre == '[') box.pop();
else return false;
break;
}
case '}' : {
if(pre == '{') box.pop();
else return false;
break;
}
}
}
}
return box.empty();
}
};
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] == '}') {
if (st.empty()) return false;
else {
char c = st.top();
st.pop();
if ((c == '(' && s[i] != ')') || (c == '[' && s[i] != ']') || (c == '{' && s[i] != '}')) return false;
}
} else st.push(s[i]);
}
return st.empty();
}
};
本文介绍了一种使用栈数据结构来验证括号是否正确配对的方法。通过遍历字符串中的每一种括号,确保它们能够按照正确的顺序闭合。具体实现包括两种情况:遇到开括号时将其压入栈中;遇到闭括号时检查栈顶元素是否为对应的开括号。
911

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



