[LeetCode-Algorithms-32] "Longest Valid Parentheses" (2017.10.19-WEEK7)

题目链接:Longest Valid Parentheses


  • 题目介绍:

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.


(1)思路:用ans计数匹配成功的前后括号数,把括号字符串依次使用stack进行压栈比较并将成功匹配的抛出。

(2)代码:

#include 
class Solution {
public:
    int longestValidParentheses(string s) {
        int ans = 0;
        stack<int> par; 
        par.push(-1);
        for (int i = 0; i <= s.length(); i++) {
            if(ans <= i-par.top()-1) ans = i-par.top()-1;
            if (i == s.length()) break;
            if (par.top() >= 0 && s[par.top()] == '(' && s[i] == ')') par.pop();
            else par.push(i);
        }
        return ans;
    }
};

(3)提交结果:

[LeetCode-Algorithms-32]

你可能感兴趣的:(LeetCode算法题目)