【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses

本文详细探讨了LeetCode上的三道括号匹配问题,包括判断字符串是否为合法括号匹配、生成所有合法括号组合以及找到最长有效括号子串的解决方案。通过递归和栈数据结构来解决这些问题,并提供了Java实现的AC代码。

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

leetcode上有三道关于括号符(‘(’,‘)’,‘[’,‘]’,‘{’,‘}’)匹配的问题,其中第三题是第一题的拓展,分别是:

(1)Valid Parentheses,判断字符串是否是合法的括号匹配字符串

(2)Generate Parentheses,根据所给的整数生成所有合法的括号匹配字符串

(3)Longest Valid Parentheses,根据所给的括号字符串,求其中最长的括号匹配字符子串

 下面分别讨论我对这三道题的思路的做法。


题目: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.

解析:已知字符串包含‘(’、‘)’、‘[’、‘]’、‘{’、‘}’ 六种字符,判断其是否为合法的字符串,是否合法的标准是每种类型括号的左右括号匹配。主要解法是用“栈”(Stack)来维护当前的字符串,如果遇到三种左括号即‘(’、‘[’、‘{’,直接将当前符号push栈中,如果遇到三种右括号‘)’、‘]’、‘}’,需要判断栈顶层的括号类型是否为匹配的右括号。
Java AC代码:

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

题目:Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

解析:输入正整数n表示生成括号的对数,要求输出所有的括号组合(该题只有小括号)。我对于该题的解决思路是用dfs,针对当前的字符串可以选择添加左括号或者右括号。当前括号数中的左括号数小于右括号数,或者左括号书超出n,右括号书超出n,表示这种字符串肯定不符合要求,不继续进行下一次递归。

Java AC代码:

public class Solution {

	List<String> result = new ArrayList<String>();

	public List<String> generateParenthesis(int n) {
		recursion(n, 0, 0, "");
		return result;
	}

	public void recursion(int n, int left, int right, String str) {
		if (left < right || left>n || right>n) {
			return;
		} else if (left == right && left + right == 2 * n) {
			result.add(str);
			return;
		} else {
			recursion(n,left+1,right,str+"(");
			recursion(n,left,right+1,str+")");
		}
	}

}

题目:Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

解析:根据已给字符串判断其中包含的最长字符匹配的子串(只有小括号字符)。该题判断括号字符串有效性的思路可以参照第一题Valid Parentheses,如果是左括号,直接放入“栈”(Stack)中,如果是右括号,判断栈中是否有左括号和自己匹配。

注意和第一题的一个重要区别是该题要计算最长字符匹配的子串的长度,所以栈中应当存放对应的左括号在字符串中的位置。

Java AC代码:

public class Solution {
	
	public int longestValidParentheses(String s) {
		int res = 0, lastLeft = 0;
		Stack<Integer> stack = new Stack<Integer>();
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '(') {
				stack.push(i);
			} else if (!stack.isEmpty()) {
				stack.pop();
				if (stack.empty()) {
					res = res > (i - lastLeft + 1) ? res : (i - lastLeft + 1);
				} else {
					res = res > (i - stack.peek()) ? res : (i - stack.peek());
				}
			} else {
				lastLeft = i + 1;
			}
		}
		return res;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值