// Author: Dean Wunder (d.wunder@unsw.edu.au)
// Implementation in Live Stream by Marc Chee (November 2020)
// Implementation wasn't tested, but will hopefully mostly work!
// Using a stack to match brackets
#include <stdio.h>
#include "stack.h"
int opening_bracket(int bracket);
int closing_bracket(int bracket);
int brackets_match(int opening, int closing);
int main(int argc, char *argv[]) {
// make a stack
// loop through argv[1]
// for each element, if it's opening, add it to the stack
// if it's closing, pop from the stack if they match
// if they don't match, report invalid
Stack bracket_stack = create_stack();
int i = 0;
while (argv[1][i] != '\0') {
if (opening_bracket(argv[1][i])) {
// it's an opening bracket, add it to the stack
stack_push(bracket_stack, argv[1][i]);
} else if (closing_bracket(argv[1][i])) {
// it's a closing bracket, check if it matches
// the most recent opening bracket
if (stack_size(bracket_stack) <= 0) {
// No more opening brackets in the stack to match
// this closing bracket
printf("Invalid string, brackets didn't match.\n");
return 1;
}
int top = stack_pop(bracket_stack);
if (brackets_match(top, argv[1][i])) {
// brackets matched
} else {
// brackets didn't match . . . we have an invalid string
printf("Invalid string, brackets didn't match.\n");
return 1;
}
}
}
if (stack_size(bracket_stack) == 0) {
printf("All brackets match!\n");
} else {
printf("Invalid string, brackets didn't match.\n");
return 1;
}
return 0;
}
int opening_bracket(int bracket) {
if (bracket == '(' || bracket == '{' || bracket == '[') {
return 1;
}
return 0;
}
int closing_bracket(int bracket) {
if (bracket == ')' || bracket == '}' || bracket == ']') {
return 1;
}
return 0;
}
int brackets_match(int opening, int closing) {
if (opening == '(' && closing == ')') {
return 1;
}
if (opening == '{' && closing == '}') {
return 1;
}
if (opening == '[' && closing == ']') {
return 1;
}
return 0;
}
Resource created Friday 27 November 2020, 04:07:17 PM.
file: bracket_match.c