給定字符串(僅含 '(', ')', '[', ']'),判斷括號是否完全配對。多測試用例,長度 < 10000。
掃描字符串,遇到左括號入棧;遇到右括號檢查棧頂是否為對應左括號,是則出棧,否則不合法。掃描結束後棧為空則合法。用陣列模擬棧,top 指向下一個入棧位置。
#include <stdio.h>
#include <string.h>
#define MAXN 10000+10
char a[MAXN], b[MAXN];
int main() {
int n; scanf("%d", &n); getchar();
while (n--) {
gets(a); int top = 1, len = strlen(a);
b[top++] = a[0];
for (int i = 1; i < len; i++) {
if (a[i] == '(' || a[i] == '[') b[top++] = a[i];
else {
if (a[i] == ')' && b[top-1] == '(') --top;
else if (a[i] == ']' && b[top-1] == '[') --top;
else b[top++] = a[i];
}
}
if (top == 1) printf("Yes\n"); else printf("No\n");
}
return 0;
}
經典棧應用,邊界處理正確(空串視為合法,但題目保證非空)。時間 O(L),空間 O(L)。