Created
February 17, 2022 22:17
-
-
Save Thomashrb/343e2c0683bcbe556455e8a53100f7d2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "matching_brackets.h" | |
#include <string.h> | |
struct Stack { | |
int top; | |
char data[20]; | |
}; | |
void push(struct Stack *s, char elem) { | |
s->top++; | |
s->data[s->top] = elem; | |
} | |
void pop(struct Stack *s) { | |
s->top--; | |
} | |
char peek(struct Stack *s) { return s->data[s->top]; } | |
bool is_open(char c) { return c == '{' || c == '[' || c == '('; } | |
bool is_closed(char c) { return c == '}' || c == ']' || c == ')'; } | |
char opposing(char *c) { | |
switch (*c) { | |
case '}': | |
return '{'; | |
case ')': | |
return '('; | |
case ']': | |
return '['; | |
default: | |
return '\n'; | |
} | |
} | |
bool is_paired(const char *input) { | |
struct Stack stack; | |
size_t i; | |
stack.top = -1; | |
for (i = 0; i < strlen(input); i++) { | |
char c = input[i]; | |
if (is_open(c)) { | |
push(&stack, c); | |
} else if (is_closed(c)) { | |
if (peek(&stack) == opposing(&c)) { | |
pop(&stack); | |
} else { | |
return false; | |
} | |
} else { | |
// char we do not care about | |
} | |
} | |
return stack.top == -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment