【力扣 - 有效的括号】

本文介绍了如何使用栈和哈希表的数据结构解决LeetCode中的有效括号问题,通过遍历输入字符串,确保每个右括号与相应的左括号匹配,判断字符串的有效性。时间复杂度为O(n),空间复杂度为O(n+Σ),其中n为字符串长度,Σ为字符集大小。

题目描述

给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  • 左括号必须用相同类型的右括号闭合。
  • 左括号必须以正确的顺序闭合。
  • 每个右括号都有一个对应的相同类型的左括号。

在这里插入图片描述

题解:栈

判断括号的有效性可以使用「栈」这一数据结构来解决。

我们遍历给定的字符串 s。当我们遇到一个左括号时,我们会期望在后续的遍历中,有一个相同类型的右括号将其闭合。由于后遇到的左括号要先闭合,因此我们可以将这个左括号放入栈顶。

当我们遇到一个右括号时,我们需要将一个相同类型的左括号闭合。此时,我们可以取出栈顶的左括号并判断它们是否是相同类型的括号。如果不是相同的类型,或者栈中并没有左括号,那么字符串 s 无效,返回 False。为了快速判断括号的类型,我们可以使用哈希表存储每一种括号。哈希表的key为右括号,值为相同类型的左括号。

在遍历结束后,如果栈中没有左括号,说明我们将字符串 s 中的所有左括号闭合,返回 True,否则返回 False

注意到有效字符串的长度一定为偶数,因此如果字符串的长度为奇数,我们可以直接返回 False,省去后续的遍历判断过程。

代码

// This function pairs a closing bracket/brace/parenthesis with its corresponding opening counterpart
char pairs(char a) {
	// if a closing brace is passed, return the corresponding opening brace
    if (a == '}') return '{'; 
    // if a closing bracket is passed, return the corresponding opening bracket
    if (a == ']') return '['; 
    // if a closing parenthesis is passed, return the corresponding opening parenthesis
    if (a == ')') return '('; 
    // if none of the above characters are passed, return 0
    return 0; 
}

// This function checks if a given string of brackets/braces/parentheses is valid
bool isValid(char* s) {
    int n = strlen(s); // get the length of the input string
    if (n % 2 == 1) { // if the length is odd, the string is invalid
        return false;
    }
    // create a stack to store opening brackets/braces/parentheses and initialize top to 0
    int stk[n + 1], top = 0; 
    // iterate through each character in the input string
    for (int i = 0; i < n; i++) { 
    	// get the corresponding opening character for the current closing character
        char ch = pairs(s[i]);
        // if a corresponding opening character is found
        if (ch) { 
        	// if the stack is empty or the top of the stack does not match the current opening character
            if (top == 0 || stk[top - 1] != ch) { 
                return false; // the string is invalid
            }
            top--; // pop the matching opening character from the stack
        }
        // if no corresponding opening character is found
        else { 
            stk[top++] = s[i]; // push the current character onto the stack
        }
    }
    return top == 0; // if the stack is empty at the end, the string is valid
}

复杂度分析

  • 时间复杂度:O(n),其中 n 是字符串 s 的长度。
  • 空间复杂度:O(n+∣Σ∣),其中 Σ 表示字符集,本题中字符串只包含 6 种括号,∣Σ∣=6|。栈中的字符数量为 O(n),而哈希表使用的空间为 O(∣Σ∣),相加即可得到总空间复杂度。

作者:力扣官方题解
链接:https://leetcode.cn/problems/valid-parentheses/solutions/373578/you-xiao-de-gua-hao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

力扣有效括号问题通常包含“有效括号”(LeetCode第20题)和“最长有效括号”(LeetCode第32题)两个常见问题,以下是这两个问题的C语言解决方案: ### 有效括号LeetCode第20题) 该问题要求判断给定的只包含 `(`, `)`, `{`, `}`, `[`, `]` 的字符串是否有效有效字符串需满足左括号必须用相同类型的右括号闭合,且左括号必须以正确的顺序闭合,每个右括号都有一个对应的相同类型的左括号 [^2]。 ```c bool isValid(char * s){ char stack[10240]; int i = 1; stack[0] = '0'; while(*s!='\0'){ if(*s=='(' || *s=='[' || *s=='{'){ stack[i++] = *s; } else if(*s==')' ){ if(stack[i-1]!='(' ) return false; else i--; } else if(*s==']'){ if(stack[i-1]!='[' ) return false; else i--; } else if(*s=='}'){ if(stack[i-1]!='{' ) return false; else i--; } s++; } if(i==1) return true; else return false; } ``` ### 最长有效括号LeetCode第32题) 此问题需要找出给定字符串中最长的有效括号子串的长度。 #### 方法一:两次遍历法 ```c #include <stdio.h> #include <string.h> int main(void) { int i, ilen, imax = 0, ileft = 0, iright = 0; char str[100001] = { 0 }; scanf("%s", str); ilen = strlen(str); // 从左往右匹配 for (i = 0; i < ilen; i++) { if (str[i] == '(') { ileft++; } else if (str[i] == ')') { iright++; if (ileft == iright) { imax = ileft > imax ? ileft : imax; } else if (iright > ileft) { ileft = 0; iright = 0; } } } ileft = 0; iright = 0; // 从右往左匹配 for (i = ilen - 1; i >= 0; i--) { if (str[i] == ')') { iright++; } else if (str[i] == '(') { ileft++; if (ileft == iright) { imax = ileft > imax ? ileft : imax; } else if (ileft > iright) { ileft = 0; iright = 0; } } } printf("%d\n", 2 * imax); return 0; } ``` #### 方法二:动态规划法 ```c int max(int a, int b) { return a > b ? a : b; } int longestValidParentheses(char* s) { const int len = strlen(s); if (!len) { return 0; } int dp[len]; memset(dp, 0, sizeof(dp)); int maxLen = 0; for (int i = 1; i < len; i++) { if (s[i] == ')') { int preIndex = i - 1 - dp[i - 1]; if (preIndex >= 0 && s[preIndex] == '(') { dp[i] = dp[i - 1] + 2 + (preIndex - 1 >= 0 ? dp[preIndex - 1] : 0); maxLen = max(maxLen, dp[i]); } } } return maxLen; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六月悉茗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值