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

来源:互联网 发布:艾瑞数据查询 编辑:程序博客网 时间:2024/06/09 16:37

题目链接: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 <stack>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)提交结果:

这里写图片描述

原创粉丝点击