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
  • 1167

leetcode-32. Longest Valid Parentheses

leetcode-32. Longest Valid Parentheses - 如果是左括号就将当前位置压人栈, - 如果是右括号就判断当前栈是否为空, - 如果是空则说明之前数据违法...

leetcode 32 -- Longest Valid Parentheses

Longest Valid Parentheses 题目: Given a string containing just the characters ‘(’ and ‘)’, find t...

[LeetCOde32]Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (we...
  • sbitswc
  • sbitswc
  • 2014年06月15日 00:17
  • 594

32. Longest Valid Parentheses

主要参考:http://blog.csdn.net/feliciafay/article/details/20686595,该方法的时间复杂度为O(n)。 C++代码:class Solution ...

leetcode 32. Longest Valid Parentheses——(use stack)

import java.util.Stack; //Given a string containing just the characters '(' and ')', find the lengt...

leetcode笔记:32.Longest Valid Parentheses

题目要求:string s 只包含 '(' 和 ‘)’ 寻找最长valid长度。 Given a string containing just the characters '(' and ...

LeetCode(32)Longest Valid Parentheses

题目如下: Given a string containing just the characters '(' and ')', find the length of the longest vali...

Leetcode32:Longest Valid Parentheses

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

[leetcode] 32. Longest Valid Parentheses 解题报告

题目链接:https://leetcode.com/problems/longest-valid-parentheses/ Given a string containing just the c...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Hard-题目36:32. Longest Valid Parentheses
举报原因:
原因补充:

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