您的位置:首页 > 其它

2017-09-21 LeetCode_032 Longest Valid Parentheses

2017-09-21 22:04 465 查看
.32. Longest Valid Parentheses

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:

#include <stack>


2

class Solution {


3

public:


4

   int longestValidParentheses(string s) {


5

       int ans = 0;


6

       stack<int> used; used.push(-1);


7

       for (int i = 0; i <= s.length(); i++) {


8

           ans = ans > i-used.top()-1 ? ans : i-used.top()-1;


9

           if (i == s.length()) break;


10

if (used.top() >= 0 && s[used.top()] == '(' && s[i] == ')') used.pop();


11

           else used.push(i);


12

}


13

return ans;


14

   }


15

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode