1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| // 有效的括号.cpp: 定义控制台应用程序的入口点。 //
#include "stdafx.h" #include <iostream> #include <stack> #include <string> using namespace std;
struct Node { int nums; char data; Node *next; Node() { nums = 0; data = 0; next = NULL; } }; struct Stack { Node *top = new Node(); void Push(int value) { Node *new_node = new Node(); new_node->data = value; new_node->next = top->next; top->next = new_node; top->nums++; } int Pop() { int result = top->next->data; top->next = top->next->next; top->nums--; return result; } bool empty() { return top->nums == 0; } }; class Solution { public: bool isValid(string s) { Stack *T1 = new Stack();; if (s.length() % 2 != 0) return false; if (s[0] == ')' || s[0] == ']' || s[0] == '}') return false; int length = s.length(); for (int i = 0; i < length; i++) { if (s[i] == '(') T1->Push(')'); else if (s[i] == '[') T1->Push(']'); else if (s[i] == '{') T1->Push('}'); else if (s[i] == ')') { if (T1->Pop() != ')') return false; } else if (s[i] == ']') { if (T1->Pop() != ']') return false; } else { if (T1->Pop() != '}') return false; } } if (T1->empty()) { return true; } else return false; } };
int main() { Solution s; string s1; while (cin >> s1) { cout << s.isValid(s1) << endl; } return 0; }
|