Hard-题目36:32. Longest Valid Parentheses

转载 2016年05月31日 23:45:43

题目原文:
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.
题目大意:
给出一个括号字符串,求最长的合法匹配的子串的长度。
题目分析:
用一个栈维护,如果遇到左括号则把它的下标入栈,如果遇到右括号,则记录右括号和左括号间的长度记为curLen,并判断curlen是否大于最大值max,如果是则更新。总共扫描一遍就可以了。
源码:(language:cpp)

class Solution {
public:
 // Using a stack. One pass
    int longestValidParentheses(string s) {
        vector<int> stack;
        int maxLen = 0;
        for (int i = 0; i < s.size(); ++i)
        {
            if (s[i] == '(')
                stack.push_back(i);
            else {
                if (!stack.empty() && s[stack.back()] == '(') {
                    stack.pop_back();
                    int lastPos = -1;
                    if (!stack.empty())
                        lastPos = stack.back();
                    int curLen = i - lastPos;
                    maxLen = (maxLen < curLen) ? curLen : maxLen;
                } else
                    stack.push_back(i);
            }
        }
        return maxLen;
    }
};

成绩:
12ms,15.70%,8ms,43.95%
cmershen的碎碎念:
遇到表达式计算、括号匹配这类问题时,经常要考虑堆栈的特性。

相关文章推荐

[LeetCode] 032. Longest Valid Parentheses (Hard) (C++)

[LeetCode] 032. Longest Valid Parentheses (Hard) (C++)
  • hcbbt
  • hcbbt
  • 2015-03-13 15:51
  • 1075

Leetcode 32. Longest Valid Parentheses

问题描述 Given a string containing just the characters '(' and ')', find the length of the longe...

LeetCode_32---Longest Valid Parentheses

Longest Valid Parentheses  Total Accepted: 36685 Total Submissions: 176120My Submissions Quest...

[LeetCode]32.Longest Valid Parentheses

题目Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (w...

leetcode 32. Longest Valid Parentheses

leetcode 32. Longest Valid Parentheses 算法就是从左向右扫描,遇到左括号就入栈,遇到右括号有三种情况: 1.栈顶是左括号,那么用2取代那个左括号,这时如果栈顶下边...

LeetCode (32) Longest Valid Parentheses

题目Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (w...

Leetcode #32. Longest Valid Parentheses 最长括号对 结题报告

1 结题思想题目会给出一定的“((())))”等的括号对,问你说最长的有效括号对是多长?这道题,需要用Stack,并且不能单纯的统计(或),且出栈,其大致有如下的规则:1、遇到(要压栈当前位置 2、...

32. Longest Valid Parentheses

有效连续括号最长值

32. Longest Valid Parentheses

栈的典型应用。能想到栈,但是能想到Push字符索引,真的不是很容易(这道题一般的想法是存储‘(’ ‘)’这些符号)。 原题 Given a string containing just the ...

leetcode32_Longest Valid Parentheses

一.问题描述 Given a string containing just the characters '(' and ')', find the length of the longest ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)