美文网首页动态规划
32. Longest Valid Parentheses

32. Longest Valid Parentheses

作者: RobotBerry | 来源:发表于2017-05-10 16:05 被阅读106次

    问题

    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.

    分析

    方法一:栈

    遍历字符串,如果当前字符为 ( , 入栈;如果是 ) ,检测栈的情况:如果栈为空,入栈;否则检查栈顶,如果为 ( ,出栈;否则入栈。注意,也要把当前字符的下标入栈。
    将栈的元素一一出栈,即可得到每一段合法的括号表达式的长度。假设字符串为")()(()))()(",遍历完之后,栈应该变成 ) 0, ) 7, ( 10。可以清楚地看到,原字符串有两段合法的括号表达式,长度分别为7 - 0 - 1 = 6、10 - 7 - 1 = 2。最长长度为6。

    方法二:动态规划

    假设待验证字符串为S

    1. 状态表
      dp[i] 表示以S[i - 1]作为结尾的最长合法字符串的长度
    2. 初始状态
      dp[0] = dp[1] = 0 长度为0或者1的字符串显然不合法
    3. 状态转移方程
      dp[i] = dp[i - 2] + 2 if s[i - 1] == ')' && s[i - 2] = '('
      注:表示这种情况:...() **
      显然dp[i]的大小等于...的最大合法字符串的长度(dp[i - 2])+2
      dp[i] = dp[i - 1] + 2 + dp[i - 2 - dp[i - 1]]; if s[i - 1] == ')' && s[i - 2] = ')' && s[i - 2 - dp[i - 1]] == '('
      注:表示这种情况:
      ...(()) **
      第一个 ( 是s[i - 2 - dp[i - 1]] ,第一个 ) 是s[i - 2],第二个 ) 是s[i - 1]。总长度=...的最大合法字符串的长度(dp[i - 2 - dp[i - 1]])+ 2(s[i - 2 - dp[i - 1]]和s[i - 1]匹配的一对括号)+ dp[i - 1](中间的两个括号)

    要点

    • 熟练运用栈和动态规划;
    • 动态规划分为两种,一种状态本身就是所求的变量,另一种则不是,但是所求的变量可以在更新状态表的过程中得到。

    时间复杂度

    O(n)

    空间复杂度

    O(n)

    代码

    方法一

    class Solution {
    public:
        int longestValidParentheses(string s) {
            stack<pair<char, int>> es;
            for (int i = 0; i < s.size(); i++) {
                if (es.empty() || s[i] == '(') es.push(make_pair(s[i], i));
                else {
                    if (es.top().first == '(') es.pop();
                    else es.push(make_pair(s[i], i));
                }
            }
    
            int longestLen = 0, last = s.size();
            while (!es.empty()) {
                longestLen = max(longestLen, last - es.top().second - 1);
                last = es.top().second;
                es.pop();
            }
            longestLen = max(longestLen, last);
            return longestLen;
        }
    };
    

    方法二

    class Solution {
    public:
        int longestValidParentheses(string s) {
            int n = s.size();
            vector<int> dp(n + 1, 0);
            int longestLen = 0;
            for (int i = 2; i <= n; i++) {
                if (s[i - 1] == ')') {
                    if (s[i - 2] == '(') 
                        dp[i] = dp[i - 2] + 2;
                    else if (s[i - 2 - dp[i - 1]] == '(')
                        dp[i] = dp[i - 1] + 2 + dp[i - 2 - dp[i - 1]];
                    longestLen = max(longestLen, dp[i]);
                }
            }
            return longestLen;
        }
    };
    

    相关文章

      网友评论

        本文标题:32. Longest Valid Parentheses

        本文链接:https://www.haomeiwen.com/subject/egcgtxtx.html