leetcode 32 最长有效括号

package com.feng.testproject.algorithm;

import java.util.ArrayDeque;
import java.util.Queue;

public class L32 {
    public static void main(String[] args) {
        String s = ")()())()()(";
        int i = longestValidParentheses(s);
        System.out.println(i);
    }
    public static int longestValidParentheses(String s) {
        int[][] result = new int[2][s.length()];
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                result[0][i] = 1;
            } else {
                boolean flag = true;
                for (int j = i-1; j >= 0; j--) {
                    if (result[0][j] == 1 && s.charAt(j) != ')') {
                        result[1][i] = 1;
                        result[0][j] = 0;
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    result[0][i] = 1;
                }
            }
        }
        int count = 0;
        int re = 0;
        for (int i = s.length()-1; i >=0; i--) {
            if (result[0][i] == 1) {
                count = 0;
            }
            if (result[1][i] == 1) {
                count++;
                re = Math.max(re, count);
            }
        }
        return re*2;
    }
    public static int longestValidParenthesesError(String s) {
        Queue<String> queue = new ArrayDeque<>();
        Queue<String> start = new ArrayDeque<>();
        int result = 0;
        int count = 0;
        int temp = 0;
        for (int i = 0; i < s.length(); i++) {
             if (s.charAt(i) == '(') {
                queue.offer(")");
                start.offer("(");
             }else {
                 String first = ((ArrayDeque<String>) queue).pollFirst();
                 queue.peek();
                 if (first != null && first.equals(")")) {
                     count++;
                     start.poll();
                     if (start.size() != 0) {
                         result = Math.max(result, count-temp);
                         temp++;
                     }
                 } else {
                     result = Math.max(result, count);
                     count = 0;
                     temp = 0;
                 }
                 if (queue.size() == 0) {
                     temp = count;
                     result = Math.max(result, count);
                 }
             }
        }
        if (start.size() != 0) {
            count = count - temp;
        }
        result = Math.max(result, count);
        return result*2;
    }
}

总结

做题时考虑不多,刚开始想用队列解决,结果不可行,没有想到栈。
对于动态规划没有相处转移方程,这里使用动态规划思想里记录数据状态解决

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值