Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to check if a string contains only valid parentheses (open close same type (), {}, []) in C

1 Answer

0 votes
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
 
typedef struct {
    char* data;
    int top;
    int capacity;
} Stack;
 
void initialize(Stack* stack) {
    stack->data = malloc(sizeof(char) * 10);
    stack->top = -1;
    stack->capacity = 10;
}
 
void push(Stack* stack, char ch) {
    if (stack->top == stack->capacity - 1) {
        stack->capacity *= 2;
        stack->data = realloc(stack->data, sizeof(char) * stack->capacity);
    }
     
    stack->data[++stack->top] = ch;
}
 
char pop(Stack* stack) {
    if (stack->top == -1) {
        return '\0';
    }
     
    return stack->data[stack->top--];
}
 
bool string_contains_valid_parentheses(char* s) {
    Stack stack;
     
    initialize(&stack);
     
    for (int i = 0; s[i] != '\0'; i++) {
        if (s[i] == '(') {
            push(&stack, ')');
        }
        else if (s[i] == '{') {
            push(&stack, '}');
        }
        else if (s[i] == '[') {
            push(&stack, ']');
        }
        else if (stack.top == -1 || pop(&stack) != s[i]) {
            free(stack.data);
            return false;
        }
    }
    
    free(stack.data);
    
    return stack.top == -1;
}
 
int main() {
    printf("%s\n", string_contains_valid_parentheses("(){}[]()(){}") ? "true" : "false");
     
    return 0;
}
 
 
   
   
   
/*
run:
   
true
   
*/

 



answered Mar 9, 2024 by avibootz
edited Mar 9, 2024 by avibootz
...