
【学习版】
【C语言】
【C++】
#include<iostream>
class MyStack {
public:
struct Node {
char val;
Node* prev;
Node* next;
Node(char x) :val(x), prev(NULL),next(NULL) {};
};
MyStack() {
base = new Node('0');
top = base;
}
bool empty() {
return top == base;
}
void push(int x) {
Node* newNode = new Node(x);
top->next = newNode;
newNode->prev = top;
top = top->next;
}
void pop() {
Node* tmp = top;
top = top->prev;
delete tmp;
}
char Top() {
return top->val;
}
private:
Node* base;
Node* top;
};
int main() {
std::string s;
MyStack stk;
std::cin >> s;
for (int i = 0; i < s.size(); i++) {
if (!stk.empty() && s[i] == ')') {
if (stk.Top() == '(') {
stk.pop();
continue;
}
}
if (!stk.empty() && s[i] == ']') {
if (stk.Top() == '[') {
stk.pop();
continue;
}
}
stk.push(s[i]);
}
if (stk.empty()) {
std::cout << "YES";
}
else std::cout << "NO";
return 0;
}
【STL】
#include<iostream>
#include<stack>
void solve() {
std::string s;
std::stack<char> stk;
std::cin >> s;
for (int i = 0; i < s.size(); i++) {
if (!stk.empty()&&s[i] == ')') {
if (stk.top() == '(') {
stk.pop();
continue;
}
}
if (!stk.empty()&&s[i] == ']') {
if (stk.top() == '[') {
stk.pop();
continue;
}
}
stk.push(s[i]);
}
if (stk.empty()) {
std::cout << "YES";
}
else std::cout << "NO";
return;
}
int main() {
solve();
return 0;
}