C语言题目六

#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;  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值