Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bb764e4

Browse files
author
fupengfei
committed
12/25 COMMIT
1 parent ac96524 commit bb764e4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*Longest Valid Parentheses:Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.*/
2+
class Solution {
3+
public:
4+
int longestValidParentheses(string s) {
5+
int ls = s.size();
6+
int res = 0;
7+
int cnt;
8+
unordered_map<int, int> um;
9+
10+
int i;
11+
cnt = 0;
12+
um[0] = -1;
13+
for (i = 0; i < ls; ++i) {
14+
if (s[i] == '(') {
15+
++cnt;
16+
if (um.find(cnt) == um.end()) {
17+
um[cnt] = i;
18+
}
19+
} else if (s[i] == ')') {
20+
if (um.find(cnt) != um.end()) {
21+
um.erase(cnt);
22+
}
23+
--cnt;
24+
if (um.find(cnt) == um.end()) {
25+
um[cnt] = i;
26+
} else {
27+
res = max(res, i - um[cnt]);
28+
}
29+
}
30+
}
31+
um.clear();
32+
33+
return res;
34+
}
35+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /