LeetCode - Valid Parenthesis

本文介绍了一种使用栈数据结构来验证括号是否正确配对的方法。对于包含'(',')','{','}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.


这道题还是比较简单的,看到左括号就入栈,右括号出栈。出栈后对比被出栈的左括号和当前的右括号是否匹配。

注意特殊情况,即字符串匹配完了,如果栈内还有左括号,则说明有的左括号没有被匹配上,以及当前是右括号时,栈内没有了,说明这个右括号也没匹配上。

public class Solution {
    public boolean isValid(String s) {
        if(s==null || s.length()==0) return true;
        Stack<Character> stack = new Stack<Character>();
        for(int i=0; i<s.length(); i++){
            if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){
                stack.push(s.charAt(i));
            }
            else{
                if(stack.isEmpty()) return false;
                char c = stack.pop();
                if(c=='(' && s.charAt(i)==')') continue;
                if(c=='{' && s.charAt(i)=='}') continue;
                if(c=='[' && s.charAt(i)==']') continue;
                else return false;
            }
        }
        if(stack.isEmpty()) return true;
        return false;
    }
}


### 深度优先搜索 (DFS) 在括号匹配问题中的应用 深度优先搜索(Depth First Search, DFS)是一种常用的图遍历算法,在解决括号匹配问题时,可以通过递归的方式探索所有可能的组合来寻找有效的解决方案。下面详细介绍其在括号匹配问题中的具体应用。 #### 1. 基本原理 DFS 的核心在于通过递归方式逐步构建候选解,并验证这些解是否满足约束条件。对于括号匹配问题,通常需要移除最少数量的无效括号以使剩余部分成为合法的括号序列[^1]。此过程涉及以下几个方面: - **状态表示**:记录当前处理的位置以及已删除的左/右括号的数量。 - **剪枝策略**:如果发现某条路径不可能得到有效解,则提前终止该分支的进一步探索。 - **合法性检测**:利用栈或其他方法实时检查括号序列的有效性。 #### 2. Python 示例代码 以下是一个基于 LeetCode 题目 “301. Remove Invalid Parentheses” 的实现案例: ```python def removeInvalidParentheses(s): result = [] visited = set() def isValid(string): count = 0 for char in string: if char == '(': count += 1 elif char == ')': count -= 1 if count < 0: return False return count == 0 def dfs(current_str): if current_str in visited or not current_str: return visited.add(current_str) if isValid(current_str): result.append(current_str) return for i in range(len(current_str)): if current_str[i].isalpha(): continue new_str = current_str[:i] + current_str[i+1:] if new_str not in visited: dfs(new_str) dfs(s) max_len = max([len(r) for r in result]) if result else 0 final_result = [r for r in result if len(r) == max_len] return list(set(final_result)) ``` 上述代码定义了一个 `removeInvalidParentheses` 函数用于去除非法括号并返回所有可能的结果集合。其中采用了递归来尝试每种可能性,并借助辅助函数 `isValid()` 来判断某个字符串是否构成有效的括号序列。 #### 3. C++ 示例代码 除了 Python 外,也可以采用其他编程语言如 C++ 实现相同功能。这里给出一个简单的例子展示如何使用 Boost 库完成类似的任务[^3]: ```cpp #include <boost/graph/adjacency_list.hpp> #include <string> using namespace std; using namespace boost; bool isBalanced(const string& s){ int balance=0; for(auto c:s){ if(c=='(') ++balance; if(c==')') --balance; if(balance<0) return false; // More closing than opening } return balance==0; } void findValidExpressions(string expr,int pos,string path,set<string>& res,bool removed=false){ if(pos==(int)expr.size()){ if(isBalanced(path)) res.insert(path); return ; } char ch=expr[pos]; if(ch!='(' && ch!=')'){ findValidExpressions(expr,pos+1,path+ch,res,removed); // Keep this character unchanged. }else{ // Option 1: Skip the current parenthesis. if(!removed){ // Only allow skipping once per branch to avoid duplicates. findValidExpressions(expr,pos+1,path,res,true); } // Option 2: Include it and proceed further down the tree. findValidExpressions(expr,pos+1,path+ch,res,removed); } } ``` 这段代码同样实现了查找所有可能的有效括号表达式的逻辑,不过它是用标准模板库(STL)而非第三方框架编写而成。 #### 结论 无论是哪种具体的实现形式,都可以看出 DFS 是一种非常强大且灵活的技术手段,尤其适合用来求解那些具有复杂约束关系的问题比如括号匹配等。它允许我们在庞大的搜索空间里高效地定位目标子集而无需穷举全部候选项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值