用c++设计一个算法判断圆括号是否正确配对
时间: 2024-05-02 16:21:39 浏览: 75
1. 定义一个栈结构,用于存储左括号;
2. 遍历字符串中的每一个字符,如果是左括号,将其压入栈中;
3. 如果是右括号,判断栈是否为空,如果为空则说明出现了没有匹配的右括号,返回“不匹配”;
4. 如果栈不为空,将栈顶的左括号出栈,判断左右括号是否匹配,如果不匹配,返回“不匹配”;
5. 如果遍历完字符串后栈为空,则说明括号配对正确,返回“匹配”。
代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *stack) {
stack->top = -1;
}
int isEmpty(Stack *stack) {
return stack->top == -1;
}
int isFull(Stack *stack) {
return stack->top == MAX_SIZE - 1;
}
void push(Stack *stack, char ch) {
if (isFull(stack)) {
printf("Stack is full!\n");
return;
}
stack->data[++stack->top] = ch;
}
char pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty!\n");
return '\0';
}
return stack->data[stack->top--];
}
char peek(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty!\n");
return '\0';
}
return stack->data[stack->top];
}
int isMatch(char left, char right) {
if (left == '(' && right == ')') {
return 1;
}
return 0;
}
int checkParentheses(char *str) {
Stack stack;
initStack(&stack);
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] == '(') {
push(&stack, str[i]);
} else if (str[i] == ')') {
if (isEmpty(&stack)) {
return 0;
}
char left = pop(&stack);
if (!isMatch(left, str[i])) {
return 0;
}
}
}
if (isEmpty(&stack)) {
return 1;
}
return 0;
}
int main() {
char str[MAX_SIZE];
printf("Input a string: ");
scanf("%s", str);
int result = checkParentheses(str);
if (result) {
printf("Parentheses match!\n");
} else {
printf("Parentheses do not match!\n");
}
return 0;
}
```
阅读全文