Longest Valid Parentheses

每日算�'2595——leetcode系列


问题 Longest Valid Parentheses

Difficulty: Hard

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.

class Solution {
public:
    int longestValidParentheses(string s) {

    }
};

翻译

最长有效括号

难度系数:中等
给定一个仅'25E4��包含'('')'的字符串,找出其中最长有效括号组成的子集的长度。
字符串"(()",它的最长有效号符子�%;B�是"()",长度为2。
另一个例子")()())",它的最长有效括号子集是"()()",长度是4。

思路

假定:起始匹配位置startIndex=-1;最大匹配长度maxLen=0,当前遍历的索引�'25B8�i:
遍历字符串:
遍历到的字符有两种情况:

  • 当前字符为左括号,压栈, startIdnex = i;
  • 当前字符为右括号
    1. 如果栈为空,表示没有匹配的左括号,无任何操作
    2. 如果栈不空,出栈;

经过上面的第二步操作后,栈有两种情况:

  • 栈空, 则i-startIndex为当前找到的匹配长度,检查i-startIndex是否比maxLen
    更大,如果更大就更新maxLen;
  • 栈不空,则当前栈顶元素t是上次匹配的最后位置。,检查i-t
    是否比ml更大,使得ml得以更新。

    '0A

    注:因为入栈的一定是左括号,显然没�'9C�必要将它们本身入
    栈,应该入栈的是该字符在字符串中的索引。

代码

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        size_t len = nums.size();
        if (len == 1 || len == 0){
            return;
        }
        int firstBreakNum = -1;
        size_t firstBreakIndex = -1;
        for (size_t i = len ;i > '253Cspan class="hljs-number">1; --i){
            if (nums[i-1] > nums[i-2]){
                firstBreakNum = nums[i-2];
                firstBreakIndex = i - 2;
         '2520      break;
            }
        }
        // 没找到打破升序规律的,那就全部升序排列
        if (firstBreakNum == -1){
            reverse(nums.begin(), nums.end());
            return;
        }
        for (size_t i = len; i > 1; --i){
            if (nums[i-1] > firstBreakNum){
                swap(nums[i-1]'252C nums[firstBreakIndex]);
                break;
            }
        }
        auto iter = nums.begin();
        for (size_t i = 0; i < firstBreakIndex + 1; ++i){
  '20         iter++;
        }
        reverse(iter, nums.end());
    }
};

还可以继续优化

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值