usaa24/a1/program.c

68 lines
1.7 KiB
C
Raw Permalink Normal View History

2024-10-31 17:00:20 +00:00
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 100
int isMatchingPair(char open, char close)
{
return (open == '(' && close == ')') || (open == '{' && close == '}') || (open == '[' && close == ']') || (open == '<' && close == '>');
}
int main()
{
char input[MAX_LENGTH];
fgets(input, sizeof(input), stdin);
int len = strlen(input);
if (input[len - 1] == '\n')
{
input[len - 1] = '\0';
len--;
}
printf("Read: %s\n", input);
char stack[MAX_LENGTH];
int top = -1;
for (int i = 0; i < len; i++)
{
char ch = input[i];
if (ch == '(' || ch == '{' || ch == '[' || ch == '<')
{
stack[++top] = ch;
}
else if (ch == ')' || ch == '}' || ch == ']' || ch == '>')
{
2024-10-31 17:07:09 +00:00
if (top == -1)
2024-10-31 17:00:20 +00:00
{
2024-10-31 17:07:09 +00:00
printf("Unexpected closing bracket %c in %d\n", ch, i);
2024-10-31 17:00:20 +00:00
return 0;
}
else if (!isMatchingPair(stack[top], ch))
{
2024-10-31 18:07:20 +00:00
printf("Crossed bracket %c in %d, expected %c \n", ch, i, (stack[top] == '(' ? ')' : stack[top] == '{' ? '}' : stack[top] == '[' ? ']' : '>'));
2024-10-31 17:00:20 +00:00
return 0;
}
top--;
}
}
if (top != -1)
{
2024-10-31 17:42:10 +00:00
memset(input, 0, len);
sprintf(input,"Missing closing brackets: ");
len = strlen(input);
2024-10-31 17:46:56 +00:00
for (int i = top; i >= 0; i--)
2024-10-31 17:42:10 +00:00
{
input[len++] = (stack[i] == '(' ? ')' : stack[i] == '{' ? '}' : stack[i] == '[' ? ']' : '>');
}
input[len] = 0;
2024-10-31 17:44:01 +00:00
printf("%s\n", input);
2024-10-31 17:00:20 +00:00
return 0;
}
printf("All brackets OK\n");
return 0;
}