Below is the equivalent C implementation of the provided TypeScript code. The code checks whether a given string of parentheses, brackets, and braces is valid (i.e., properly balanced and nested).
Explanation of the Approach:
Stack Simulation: In TypeScript, an array is used as a stack with push and pop operations. In C, we simulate this behavior using a character array (toBeClosed) and an integer to track the top of the stack.
String Iteration: The string is iterated character by character using a for loop.
Opening Characters: If the character is an opening bracket ((, [, {), it is pushed onto the stack.
Closing Characters: If the character is a closing bracket (), ], }), the stack is checked for a matching opening bracket. If the match is incorrect or the stack is empty, the function returns false.
Final Check: After processing all characters, the stack should be empty for the string to be valid.
C Code:
c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool isValid(char* s) {
// Stack to store opening brackets
char toBeClosed[1000]; // Assuming max length of string is 1000
int top = -1; // Stack pointer (top of stack)
// Iterate through each character in the string
for (int i = 0; s[i] != '\0'; i++) {
char charAt = s[i];
// If the character is an opening bracket, push it onto the stack
if (charAt == '(' || charAt == '[' || charAt == '{') {
toBeClosed[++top] = charAt;
}
// If the character is a closing bracket
if (charAt == ')' || charAt == ']' || charAt == '}') {
// Check if the stack is empty or the top of the stack does not match
if (top == -1 ||
(charAt == ')' && toBeClosed[top] != '(') ||
(charAt == ']' && toBeClosed[top] != '[') ||
(charAt == '}' && toBeClosed[top] != '{')) {
return false; // Invalid string
}
// Pop the top element from the stack
top--;
}
}
// If the stack is empty, the string is valid
return top == -1;
}
int main() {
// Test cases
char test1[] = "()[]{}";
char test2[] = "(]";
char test3[] = "([)]";
char test4[] = "{[]}";
printf("Test 1: %s\n", isValid(test1) ? "true" : "false");
printf("Test 2: %s\n", isValid(test2) ? "true" : "false");
printf("Test 3: %s\n", isValid(test3) ? "true" : "false");
printf("Test 4: %s\n", isValid(test4) ? "true" : "false");
return 0;
}
Key Points:
Stack Implementation: The stack is implemented using a fixed-size array (toBeClosed) and an integer (top) to track the current position.
Character Matching: The logic for matching opening and closing brackets is directly translated from the TypeScript code.
Edge Cases: The function handles edge cases such as an empty string (valid) or unmatched brackets (invalid).
Example Output:
For the provided test cases:
Input: "()[]{}" → Output: true
Input: "(]" → Output: false
Input: "([)]" → Output: false
Input: "{[]}" → Output: true
This implementation ensures correctness and clarity while adhering to C conventions.