題目鏈接:點擊打開鏈接
題意:給定一個合法的序列,刪掉所有不必要的括號。
#include#include const int MAX_N = 10007; char a[MAX_N]; int stack[MAX_N], top; bool mark[MAX_N], stacknow[MAX_N]; int main() { while (1 == scanf("%s", a)) { int len = (int) strlen(a); top = 0; memset(mark, false, sizeof mark); for (int i = 0; i < len; ++i) { if (a[i] == '(') { stack[top++] = i; stacknow[top - 1] = false; } else if (a[i] == '+') { if (top) { stacknow[top - 1] = true; } } else if(a[i] == ')') { if ((stacknow[top - 1] && (stack[top - 1] - 1 >= 0 && a[stack[top - 1] - 1] != '+' && a[stack[top - 1] - 1] != '(' || i + 1 < len && a[i + 1] != '+' && a[i + 1] != ')')) == 0) { if (stack[top - 1] - 1 >= 0 && a[stack[top - 1] - 1] == '(' && i + 1 < len && a[i + 1] == ')') stacknow[top - 2] = stacknow[top - 1]; mark[stack[top - 1]] = mark[i] = true; } --top; } } for (int i = 0; i < len; ++i) { if (!mark[i]) putchar(a[i]); } puts(""); } return 0; }