请编写程序判断一个包含“(”和“)”的括号序列是否匹配。如匹配则输出Match;如不匹配,计算出使该序列变为匹配序列所需添加的最少括号数目(只允许在该序列开始和结尾处添加括号),并输出经添加最少括号后得到的合法匹配序列。 用c写出
时间: 2024-09-30 11:02:41 浏览: 27
C实现的括号匹配问题,主要由栈实现
下面是一个C程序,用于判断括号序列是否匹配,并计算若不匹配所需的最少括号数。我们将使用栈数据结构来处理这个问题。
```c
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char* data;
size_t size;
} Stack;
bool isEmpty(Stack* stack) {
return stack->size == 0;
}
void push(Stack* stack, char c) {
stack->data = realloc(stack->data, sizeof(char) * (stack->size + 1));
stack->data[stack->size] = c;
stack->size++;
}
char pop(Stack* stack) {
if (isEmpty(stack)) {
return '\0'; // 表示栈空
}
char c = stack->data[stack->size - 1));
stack->size--;
return c;
}
bool isMatching(char open, char close) {
return open == ')' && close == '(' ||
open == '}' && close == '{' ||
open == ']' && close == '[';
}
bool isValidBrackets(char* brackets) {
Stack stack;
stack.size = 0;
for (size_t i = 0; brackets[i]; i++) {
if (brackets[i] == '(' || brackets[i] == '{' || brackets[i] == '[') {
push(&stack, brackets[i]);
} else if (!isEmpty(&stack) && isMatching(brackets[i], pop(&stack))) {
continue;
} else {
return false;
}
}
return isEmpty(&stack);
}
int minBalloonsToMatch(char* brackets) {
if (isValidBrackets(brackets)) {
return 0;
}
size_t unmatched_closing_brackets = 0;
for (size_t i = 0; brackets[i]; i++) {
if (brackets[i] == ')' || brackets[i] == '}' || brackets[i] == ']') {
unmatched_closing_brackets++;
}
}
return unmatched_closing_brackets;
}
void addBalloonsAndPrint(char* brackets, int num_to_add) {
char new_brackets[strlen(brackets) + num_to_add * 2 + 1];
strcpy(new_brackets, "(");
strcat(new_brackets, brackets);
strcat(new_brackets, ")");
printf("Add %d pairs to make it valid: (%s)\n", num_to_add, new_brackets);
}
int main() {
char* brackets = "())";
int match = isValidBrackets(brackets);
int num_to_add = minBalloonsToMatch(brackets);
if (match) {
printf("Match\n");
} else {
addBalloonsAndPrint(brackets, num_to_add);
}
return 0;
}
```
这个程序首先定义了一个栈和几个辅助函数,然后通过`isValidBrackets`函数检查括号序列是否匹配,如果匹配则直接打印Match。如果不匹配,则计算未配对的关闭括号数量,并在主函数中调用`addBalloonsAndPrint`函数生成新的匹配序列。
阅读全文