Skip to content

Instantly share code, notes, and snippets.

@lotabout
Created January 12, 2015 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lotabout/d60339e70211cf60d8c2 to your computer and use it in GitHub Desktop.
Save lotabout/d60339e70211cf60d8c2 to your computer and use it in GitHub Desktop.
validate if a sequence of push/pop is valid.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <stdbool.h>
bool check(int max, char *p)
{
/* simulate the push/pop of stacks */
bool *stack = (bool *)malloc((max+1) * sizeof(*stack));
memset(stack, true, (max+1) * sizeof(*stack));
bool valid = true;
int top = *p - '0';
stack[0] = false;
stack[top] = false;
p++;
while (*p) {
int index = *p - '0';
if (top < index) {
top = index;
} else {
for (; top > index; top--) {
if (stack[top]) {
valid = false;
goto end;
}
}
}
stack[top] = false;
p--;
}
end:
free(stack);
return valid;
}
int main(int argc, char *argv[])
{
char *line = NULL;
size_t len = 0;
ssize_t read;
while((read = getline(&line, &len, stdin)) != -1) {
char *p = line;
int max = 0;
/* check the max one */
while(*p) {
if (*p - '0' > max) {
max = *p - '0';
}
p++;
}
*(p-1) = '\0'; /* remove trailing newline */
printf("%s is %s\n", line, check(max, line) ? "Valid" : "Invalid");
}
free(line);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment