-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_valid_parentheses.cpp
More file actions
71 lines (67 loc) · 1.75 KB
/
longest_valid_parentheses.cpp
File metadata and controls
71 lines (67 loc) · 1.75 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
/*
* =====================================================================================
*
* Filename: longest_valid_parentheses.cpp
*
* Description: 32. Longest Valid Parentheses.
* Given a string containing just the characters '(' and ')', find the
* length of the longest valid (well-formed) parentheses substring.
*
* Version: 1.0
* Created: 04/17/19 12:47:26
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <stack>
#include <string>
class Solution
{
public:
int longestValidParentheses(std::string& s)
{
std::stack<int> idxes;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '(')
{
idxes.push(i);
}
else
{
if (!idxes.empty() && s[idxes.top()] == '(')
{
idxes.pop();
}
else
{
idxes.push(i);
}
}
}
int longest = 0;
int last = s.size();
while (!idxes.empty())
{
longest = std::max(longest, last - idxes.top() - 1);
last = idxes.top();
idxes.pop();
}
longest = std::max(longest, last);
return longest;
}
};
int main(int argc, char* argv[])
{
std::string s = ")()())";
auto count = Solution().longestValidParentheses(s);
printf("Input: %s\nOutput: %d\n", s.c_str(), count);
return 0;
}