Leetcode: Longest Valid Parentheses

来源:互联网 发布:可以让人变老的软件 编辑:程序博客网 时间:2024/06/15 06:42

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.

匹配之类的应该要想到堆栈,再用一个DP来记录以i结尾的有效字符串的最大长度。其实自己弄复杂了,堆栈里面存放index的话会简单一些。

class Solution {public:    int longestValidParentheses(string s) {        int size = s.size();        int *dp = new int[size];        int max_length = 0;        stack<char> parens;        for (int i = 0; i < size; ++i) {            dp[i] = 0;            if (s[i] == '(') {                parens.push(s[i]);            }            else {                if (!parens.empty()) {                    char tmp = parens.top();                    parens.pop();                    dp[i] = 2;                    if (dp[i-1] > 0) {                        dp[i] += dp[i-1];                    }                    int prev = i - dp[i];                    if (prev >= 0 && dp[prev] > 0) {                        dp[i] += dp[prev];                    }                                        if (dp[i] > max_length) {                        max_length = dp[i];                    }                }            }        }                delete []dp;        return max_length;    }};

堆栈里面存放索引,确实简单些。

class Solution {public:    int longestValidParentheses(string s) {        int result = 0;        vector<int> lens(s.size(), 0);        stack<int> indices;        for (int i = 0; i < s.size(); ++i) {            if (s[i] == '(') {                indices.push(i);            }            else {                if (!indices.empty()) {                    int len = i - indices.top() + 1;                    if (i - len >= 0) {                        len += lens[i-len];                    }                    lens[i] = len;                    if (len > result) {                        result = len;                    }                    indices.pop();                }            }        }                return result;    }};

0 0
原创粉丝点击