• 32. 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

    原题的意思是,找到原串中最大的括号排列正确的子串的长度。

    解决方法: 拿一个max存放目前为止最大的括号串。每次从下一位开始。 重点是怎么寻找从当前位置开始最大的匹配串: 左括号++,右括号++。判断左括号是否大于等于右括号。不满足则错误,退出。且长度为 j - i+1。

    很顺利 一遍Accept:

    class Solution {
    public:
        int longestValidParentheses(string s) {
            int max = 0;
            vector<int> num(s.length());
            for(int i = 0; i < s.length();i++){
                int left = 0,right = 0;
                for(int j = i; j < s.length(); j++){
                    if(s[j] == '(') left++;   //左括号加一
                    else right++;
                   
                    if(right > left) break;  //当前右括号大于左括号时退出
                    
                    if(left - right > s.length() - j) break;  //需要的右括号数大于要找的剩余位置数,说明不可能凑齐右括号了(这一行可减少时间复杂度)
                    
                    if(right == left) num[i] = j - i + 1;
                }
                if(max < num[i]) max = num[i];
            }
            return max;
        }
    };
  • 相关阅读:
    Python3 字典Dict(十三)
    Python3 元组Tuple(十二)
    Python3 列表List(十一)
    Python3 循环语句(十)
    Python3 条件控制(九)
    Python3 运算符(八)
    Swift3.0语法2
    Swift反射机制实现 AppDelegate 字符串获取类并成为根控制器
    Swift语法(更新)
    单例
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7845034.html
Copyright © 2020-2023  润新知