diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /valid_stack_seq.c | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'valid_stack_seq.c')
-rw-r--r-- | valid_stack_seq.c | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/valid_stack_seq.c b/valid_stack_seq.c new file mode 100644 index 0000000..5db9b75 --- /dev/null +++ b/valid_stack_seq.c @@ -0,0 +1,42 @@ +// 946. Validate Stack Sequences +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> + +/* + * given two integer arrays 'pushed' & 'popped' each with distinct + * values, return true if this could have been the result of a sequence + * of push and pop operations on an initially empty stack, or false otherwise + */ + +bool validateStackSequences(int *pushed, int pushed_size, int *popped, + int popped_size) { + int i = 0, j = 0, k = 0; + int *s = (int *)malloc(pushed_size * sizeof(int)); + while (k >= 0 && k < pushed_size && j < popped_size) { + if (k > 0 && s[k - 1] == popped[j]) { + k--; + j++; + } else { + if (i < pushed_size) { + if (pushed[i] == popped[j]) { + i++; + j++; + } else + s[k++] = pushed[i++]; + } else { + free(s); + return false; + } + } + } + free(s); + return true; +} + +int main() { + int pushed[] = {1, 2, 3, 4, 5}; + int p1[] = {4, 5, 3, 2, 1}, p2[] = {4, 3, 5, 1, 2}; + printf("%d\n", validateStackSequences(pushed, 5, p1, 5)); // expect: 1 + printf("%d\n", validateStackSequences(pushed, 5, p2, 5)); // expect: 0 +} |