口头加的题,弹幕说是leetcode32题
    image.png
    tips: 注意题干

    • 子串子数组要连续
    • 子序列是不连续的
    • 子串,思考方式,看以每个字符为结尾的情况下。

    如果套用原型,当count<0的时候,
    思路: 当count值变成0的时候,且下一个元素是右括号时,说明即将不合法,所以要结算当前有效子串的长度

    1. public static void main(String[] args) {
    2. String str = "((())))()";
    3. int l = process(str.toCharArray());
    4. System.out.println(l);
    5. }
    6. public static int process(char[] chs){
    7. int max = 0;
    8. int ans = 0;
    9. int count = 0;
    10. for(char ch: chs){
    11. if(ch == '('){
    12. count++;
    13. ans++;
    14. }else {
    15. if(count == 0){
    16. max =Math.max(ans, max);
    17. ans = 0;
    18. }else {
    19. count--;
    20. ans++;
    21. }
    22. }
    23. }
    24. return max;
    25. }

    解法2:左程云dp思路
    step1:
    image.png
    step2:做括号不可能
    image.png
    step3: 如果i位置是右括号,先看左括号,如果左括号涵盖的位置再往左一个是右括号,那么当前dp值是0,
    image.png
    如果是左括号,那么起码是dp[i-1] +2,但是还要看之前能不能连起来。
    image.png
    image.png
    image.png
    我的代码:

      public static int dp(char[] chs){
            int[] dp = new int[chs.length];
            int index = 0;
            int max = 0;
            for(char ch : chs){
                if(ch == '('){
                    dp[index] = 0;
                }else {
                    if(index-1 >=0){
                        int pre = dp[index-1];
                        if(index-pre-1>=0 && chs[index-pre-1] == '('){
                            dp[index] = dp[index-1] +2;
                            if(index-pre-2>=0){
                                dp[index] += dp[index-pre-2];
                            }
                        }
    
                    }
                    max = Math.max(dp[index], max);
                }
                index++;
            }
            return max;
        }
    

    左程云的:
    三目运算符简化代码行数。
    image.png