32-longest valid parentheses

来源:互联网 发布:淘宝网大童女裙 编辑:程序博客网 时间:2024/06/08 05:42

类别:dynamic programming
难度:hard

题目描述

这里写图片描述

算法分析

这道题目涉及到括号匹配的问题,第一想法是使用stack来实现,事实上确实可以这样做。
首先需要把字符串中的符号压栈并进行匹配判断
这里不同的时候,压入栈的不是符号而是符号所在的下标,便于后面对连续匹配符号的长度的比较。
对于最后留在栈中的下标,相邻两个下标的差减1就是连续子串的长度,对每个字串的长度进行比较得到最长字串的长度。

代码实现

class Solution {public:    int longestValidParentheses(string s) {        int n = s.length();        stack<int> mystack;        for (int i = 0; i < n; ++i) {            if (s[i] == '(') {                mystack.push(i);            } else {                if (!mystack.empty()) {                    if (s[mystack.top()] == '(') {                        mystack.pop();                    } else {                        mystack.push(i);                    }                } else {                    mystack.push(i);                }            }        }        int result = 0;        int temp = n;        while (!mystack.empty()) {            result = max(result, temp - mystack.top() - 1);            temp = mystack.top();            mystack.pop();        }        result = max(result, temp);        return result;    }};
原创粉丝点击