matching brackets (C)

This commit is contained in:
2021-08-09 12:13:53 +02:00
parent 1800162ece
commit 9174b75e65
5 changed files with 208 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
#include "matching_brackets.h"
/* See GNUmakefile below explanation
* https://github.com/braoult/exercism/blob/master/c/templates/GNUmakefile
*/
#if defined UNIT_TEST || defined DEBUG
#include <stdio.h>
#include <stdlib.h>
#endif
#define MAX_STACK 1024
static char STACK[MAX_STACK];
static int stack;
static char match[] = {
[')'] = '(',
[']'] = '[',
['}'] = '{'
};
static inline int push(char c)
{
if (stack<MAX_STACK)
return (STACK[stack++]=c);
return 0;
}
static inline int pop()
{
if (stack>0)
return STACK[--stack];
return 0;
}
bool is_paired(const char *s)
{
stack=0;
for (; *s; s++) {
switch (*s) {
case '[': case '(': case '{':
push(*s);
break;
case ']': case ')': case '}':
if (pop() != match[(int)*s])
return false;
break;
}
}
return stack==0;
}
#ifdef UNIT_TEST
int main(int ac, char **av)
{
int arg=1;
for (; arg<ac; ++arg) {
printf("paired(%s)=%d\n", av[arg], is_paired(av[arg]));
}
}
#endif

View File

@@ -0,0 +1,16 @@
#ifndef MATCHING_BRACKETS_H
#define MATCHING_BRACKETS_H
#include <stdbool.h>
bool is_paired(const char *input);
/* See GNUmakefile below for explanation
* https://github.com/braoult/exercism/blob/master/c/templates/GNUmakefile
*/
#ifdef TESTALL
#undef TEST_IGNORE
#define TEST_IGNORE() {}
#endif
#endif