zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    论文尾注后无法插入分节符
    实现java对象排序的三种方式
    java数组的定义方式
    Canvas
    正则xss
    mongoDB学习记录
    查找,学习,记录
    地址
    node实战学习纪录
    nodejs学习记录
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7845034.html
Copyright © 2011-2022 走看看