Hard-题目36: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.
题目大意:
给出一个括号字符串,求最长的合法匹配的子串的长度。
题目分析:
用一个栈维护,如果遇到左括号则把它的下标入栈,如果遇到右括号,则记录右括号和左括号间的长度记为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
上一篇Hard-题目35:224. Basic Calculator
下一篇Hard-题目37:218. The Skyline Problem
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭