diff options
| author | verdant <im@verdant.ee> | 2026-06-30 12:11:38 +0800 |
|---|---|---|
| committer | verdant <im@verdant.ee> | 2026-06-30 12:11:38 +0800 |
| commit | 455316f1396e98e46fdd43b7fad479b68da1eac0 (patch) | |
| tree | 16648edf2c939005c888ae4bb246b91d5af09a7b /leetcode/0020 | |
| download | oj-master.tar.gz oj-master.zip | |
Diffstat (limited to 'leetcode/0020')
| -rw-r--r-- | leetcode/0020/main.c | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/leetcode/0020/main.c b/leetcode/0020/main.c new file mode 100644 index 0000000..cf3a4dd --- /dev/null +++ b/leetcode/0020/main.c @@ -0,0 +1,43 @@ +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> + +bool isValid(char *s) { + int n = strlen(s); + if (n < 2) + return false; + + char *stack = (char *)malloc(sizeof(char) * (n + 1)); + int top = -1; + + for (int i = 0; i < n; i++) { + char ch = s[i]; + + if (ch == '(' || ch == '[' || ch == '{') { + stack[++top] = ch; + } else { + if (top == -1) { + return false; + } + + char topChar = stack[top--]; + + if (ch == ')' && topChar != '(') { + free(stack); + return false; + } + if (ch == ']' && topChar != '[') { + free(stack); + return false; + } + if (ch == '}' && topChar != '{') { + free(stack); + return false; + } + } + } + + bool result = (top == -1); + free(stack); + return result; +} |
