【LeetCode】括号配对系列

20. Valid Parentheses

题目:判断输入字符串的括号配对是否合法

思路:栈——当前字符为左括号时入栈,右括号则pop一个字符,看是否配对。需要注意栈为空的判断,在pop之前以及最后判断时。

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


22. Generate Parentheses

题目:输出所有合法的括号匹配形式

思路:dfs——分别判断左右括号个数,左括号数小于n,右括号数小于左括号数。有点类似于二叉树的左右子数。

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ret = new LinkedList<>();
        if(n < 1) return ret;
        String sb = new String("(");
        dfs(ret, sb, 1, 0,n);
        return ret;
    }
    public void dfs(List<String> ret, String sb, int left, int right, int n){
        if(sb.length() >= 2*n){
            ret.add(sb.toString());
            return;
        }
        else{
            if(left < n){
                dfs(ret, sb+"(", left+1, right, n);
            }
            if(right < left){
                dfs(ret, sb+")", left, right+1, n);
            }
        }
    }
}

32. Longest Valid Parentheses

题目:找到最长的合法括号配对子串长度。

思路:栈——沿用20题的思路,但是栈中压入的是括号的序号,出现配对就弹出。即栈中每两位之间下表差都是合法的长度,只要找到最大的长度就行。需要注意首尾的判断。

public class Solution {
    public int longestValidParentheses(String s) {
        int ret = 0;
        int len = s.length();
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < len; i++){
            if(s.charAt(i) == ')'){
                if(!stack.isEmpty() && s.charAt(stack.peek()) == '('){
                    stack.pop();
                    continue;
                }
            }
            stack.push(i);
        }
        int current = len;
        if(stack.isEmpty()) return len;
        while(!stack.isEmpty()){
            current = current - stack.peek() - 1;
            ret = Math.max(ret, current);
            current = stack.pop();
        }
        return Math.max(ret, current);
    }
}

还可以用动态规划来做。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值