#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_CHAR 10000 // 考虑到Data.txt中每行字符串长度小于10000
// 查找括号匹配
int isMatched(char ch) {
switch (ch) {
case ')': return 1;
case ']': return 2;
case '}': return 3;
case '>': return 4;
case '"': return 5; // 假设双引号也作为匹配符号
default: return 0;
}
}
// 对应的左括号
char matchLeft(int type) {
switch (type) {
case 1: return '(';
case 2: return '[';
case 3: return '{';
case 4: return '<';
case 5: return '"'; // 假设双引号也作为匹配符号
default: return 0;
}
}
// 检查字符串中的括号是否匹配
int checkBrackets(const char* str) {
char stack[MAX_CHAR];
int top = -1;
for (int i = 0; str[i]; i++) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{' || str[i] == '<' || str[i] == '"') {
stack[++top] = str[i];
} else if (isMatched(str[i])) {
if (top == -1) return 0; // 没有左括号与之匹配
int type = isMatched(str[i]);
if (stack[top] != matchLeft(type)) return 0; // 括号不匹配
top--; // 匹配成功,弹出栈顶元素
}
}
return top == -1; // 如果栈为空,说明所有括号都匹配成功
}
int main() {
FILE *fp_data, *fp_result;
char buffer[MAX_CHAR + 1]; // +1 for null terminator
// 打开文件
fp_data = fopen("Data.txt", "r");
if (!fp_data) {
perror("Failed to open Data.txt");
return EXIT_FAILURE;
}
fp_result = fopen("Result.txt", "w");
if (!fp_result) {
perror("Failed to open Result.txt");
fclose(fp_data);
return EXIT_FAILURE;
}
// 读取Data.txt并检查每行
while (fgets(buffer, MAX_CHAR, fp_data)) {
int len = strlen(buffer);
if (buffer[len - 1] == '\n') buffer[--len] = 0; // 去除换行符
if (checkBrackets(buffer)) {
fprintf(fp_result, "YES\n");
} else {
fprintf(fp_result, "NO\n");
}
}
// 关闭文件
fclose(fp_data);
fclose(fp_result);
return 0;
}