Longest Valid Parentheses

来源:互联网 发布:淘宝开店链接 编辑:程序博客网 时间:2024/05/01 10:02

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.

解题思路:利用stack在扫描字符串的过程中判断合法的子字符串的区间并保存起来,接下来要做的便是利用O(n)的时间复杂度合并区间,由于stack的关系,大区间的索引肯定在小区间的后面,这样我们从后往前标记区间便可以实现O(n)的时间复杂度,最终求解最长的区间即可,算法总的时间复杂度是O(n)的。

class Solution {public:    int longestValidParentheses(string s) {        int ans = 0, cnt = 0;        int sp, ep;        int size = s.length();        stack<int> stk;        vector< pair<int,int> > vec;        bool mark[100010];        memset(mark, false, sizeof(mark));        for(int i = 0; i < size; ++i) {            if(s[i] == ')') {                if(stk.empty()) {                    continue;                } else {                    vec.push_back(make_pair(stk.top(), i));                    stk.pop();                }            } else {                stk.push(i);            }        }        size = vec.size();        for(int i = size - 1; i >= 0; --i) {            sp = vec[i].first, ep = vec[i].second;            if(mark[vec[i].first]) continue;            for(int j = sp; j <= ep; ++j) {                mark[j] = true;            }        }        size = s.length();        for(int i = 0; i < size; ++i) {            if(!mark[i]) {                ans = max(ans, cnt);                cnt = 0;            } else {                cnt++;            }        }        ans = max(ans, cnt);        return ans;    }};


0 0
原创粉丝点击