Leetcode 每日刷题 --左右括号匹配

https://leetcode.com/problems/valid-parentheses/submissions/880634555/

2023/01/18, 虽迟但到,喜欢的朋友可以点赞关注,感谢支持~~~

问题描述:

给定字符串,检查括号是否匹配,例如:{}(){}, yes, {([])}, yes, {[)}, no,

结题思路:

  1. 此题思路比较简单明确,使用stack, 是左括号时入栈,右括号时出栈并检查是否匹配,

  1. 字符串扫描完需要检查栈是否为空,空代表完全匹配,

  1. leetcode C语言,C++ 尽量不要用全局变量,否则容易出现Testcase 能过,sumbit 不能过

答案C语言版本(为了满足第3条,代码涨的比较丑,还请见谅)

void push(char *stack_buf, uint32_t *used_stack, char str)
{
    stack_buf[*used_stack] = str;
    *used_stack += 1;
}

char pop(char *stack_buf, uint32_t *used_stack)
{
    *used_stack -= 1;
    return stack_buf[*used_stack];
}

bool stack_empty(char *stack_buf, uint32_t *used_stack)
{
    return *used_stack < 1 ? true : false;
}

bool parenthes_match(char a, char b)
{
    if ((a == '(' && b == ')')
        || (a == '[' && b == ']')
            || (a == '{' && b == '}'))
            return true;

    return false;
}

bool isValid(char * s) {
    char stack_buf[10000] = {0};
    uint32_t used_stack = 0;

    for (uint32_t i = 0; i < strlen(s); i++) {
        switch (s[i]) {
        case '[':
        case '(':
        case '{':
            push(stack_buf, &used_stack, s[i]);
            break;
        default:
            if (stack_empty(stack_buf, &used_stack)
                || !parenthes_match(pop(stack_buf, &used_stack), s[i]))
                return false;
            break;
        }
    }

    return stack_empty(stack_buf, &used_stack);
}

你可能感兴趣的:(Leetcode,leetcode,算法,职场和发展)