本文主要是介绍962: 括号匹配问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
【学习版】
【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;
}
这篇关于962: 括号匹配问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!