-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
longestValidParentheses.cpp
59 lines (54 loc) · 1.56 KB
/
longestValidParentheses.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Source : https://oj.leetcode.com/problems/longest-valid-parentheses/
// Author : Hao Chen
// Date : 2014-07-18
/**********************************************************************************
*
* 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.
*
*
**********************************************************************************/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int longestValidParentheses(string s) {
int maxLen = 0;
int lastError = -1;
vector<int> stack;
for(int i=0; i<s.size(); i++){
if (s[i] == '('){
stack.push_back(i);
}else if (s[i] == ')') {
if (stack.size()>0 ){
stack.pop_back();
int len;
if (stack.size()==0){
len = i - lastError;
} else {
len = i - stack.back();
}
if (len > maxLen) {
maxLen = len;
}
}else{
lastError = i;
}
}
}
return maxLen;
}
int main(int argc, char** argv)
{
string s = ")()())";
if (argc>1){
s = argv[1];
}
cout << s << " : " << longestValidParentheses(s) << endl;
return 0;
}