Topic describes

Given a only include a ‘(‘,’) ‘, ‘{‘,’} ‘, ‘/’, ‘ ‘the string s, determine whether a string is effective. A valid string must meet the following requirements: The left parenthesis must be closed with the same type of the right parenthesis. The left parentheses must be closed in the correct order.

The sample

Example 1: Input: s = “()” Output: true

Example 2: Input: s = “()[]{}” Output: true

Example 3: Input: s = “(]” Output: false

Source: LeetCode link: leetcode-cn.com/problems/va…

implementation

// Get the right parenthesis from the left parenthesis
char charMatch(char c)
{
    if (c == '(') {
        return ') ';
    } else if (c == '{') {
        return '} ';
    } else if (c == '[') {
        return '] ';
    } else {
        return - 1; }}bool isValid(char *s)
{
    // Use stack to solve the problem
    if (strlen(s) % 2! =0) {
        return false;     // Odd numbers will never match exactly
    }
    int top = - 1;         // Top of stack pointer
    char st[strlen(s) + 1];
    memset(st, 0.strlen(s) + 1);
    for (int i = 0; i < strlen(s); i++) {
        if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
            st[++top] = charMatch(s[i]);
        } else {
            if (top == - 1) {
                return false;    // Close parenthesis, then return false
            }
            if(st[top] ! = s[i]) {return false;    // The close parenthesis does not match the nearest open parenthesis, returns false
            }
            top--;               // The characters in the top position have matched, and the stack is removed}}if (top == - 1) {
        return true;             // To indicate that there are no mismatched elements in the stack, return true
    }
    return false;                // The match ends, there are still elements in the stack, return false
}
Copy the code