力扣20. 有效的括号

class Solution {
public:
    bool isValid(string s) {
        if(s.size() % 2 != 0) return false;
        stack<int> st;
        for(auto value : s) {
            if(value == '(') st.push(')');
            else if(value == '{') st.push('}');
            else if(value == '[') st.push(']');
            else if(st.empty() || value != st.top()) return false;
            else st.pop();
        }
        return st.empty();
    }
};
力扣有效括号问题通常包含“有效括号”(LeetCode20题)“最长有效括号”(LeetCode第32题)两个常见问题,以下是这两个问题的C语言解决方案: ### 有效括号LeetCode20题) 该问题要求判断给定的只包含 `(`, `)`, `{`, `}`, `[`, `]` 的字符串是否有效有效字符串需满足左括号必须用相同类型的右括号闭合,且左括号必须以正确的顺序闭合,每个右括号都有一个对应的相同类型的左括号 [^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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值