LeetCode (Longest Valid Parentheses)

来源:互联网 发布:php 获取命名空间 编辑:程序博客网 时间:2024/05/17 20:42

Problem:

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.

Solution:

class Solution {public:    int longestValidParentheses(string s) {        int max = 0, l = 0;        stack<char> p1, p2;        for (int i = 0; i < s.size(); i++){            if (p1.empty() && s[i] == ')'){                max = max > l ? max : l;                l = 0;                continue;            }else if (s[i] == '('){                p1.push(')');            }else{                p1.pop();                l += 2;            }            if (p1.empty()){                max = max > l ? max : l;            }        }        l = 0;        for (int i = s.size() - 1; i >= 0; i--){            if (p2.empty() && s[i] == '('){                max = max > l ? max : l;                l = 0;                continue;            }else if (s[i] == ')'){                p2.push('(');            }else{                p2.pop();                l += 2;            }            if (p2.empty()){                max = max > l ? max : l;            }        }        return max;    }};


0 0
原创粉丝点击