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 c349f96

Browse files
solved: Longest Valid Parentheses
1 parent c7280ab commit c349f96

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

‎README.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,4 +253,32 @@ List<int> findSubstring(String s, List<String> words) {
253253
254254
return startIndexs;
255255
}
256+
```
257+
258+
### Longest Valid Parentheses
259+
260+
```dart
261+
int longestValidParentheses(String s) {
262+
if (s.isEmpty) return 0;
263+
264+
int longest = 0;
265+
final List<int> stack = [-1];
266+
267+
for (int i = 0; i < s.length; i++) {
268+
// Open
269+
if (s[i] == '(') {
270+
stack.add(i);
271+
} else {
272+
if (stack.isNotEmpty) stack.removeLast();
273+
274+
if (stack.isNotEmpty) {
275+
longest = max(longest, i - stack.last);
276+
} else {
277+
stack.add(i);
278+
}
279+
}
280+
}
281+
282+
return longest;
283+
}
256284
```

‎longest_valid_parentheses.dart‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import 'dart:math';
2+
3+
void main(List<String> args) {
4+
List<String> cases = [
5+
"(()",
6+
")()())",
7+
"",
8+
"(",
9+
"))",
10+
"((()()",
11+
];
12+
13+
for (final testcase in cases) {
14+
print(longestValidParentheses(testcase));
15+
}
16+
}
17+
18+
int longestValidParentheses(String s) {
19+
if (s.isEmpty) return 0;
20+
21+
int longest = 0;
22+
final List<int> stack = [-1];
23+
24+
for (int i = 0; i < s.length; i++) {
25+
// Open
26+
if (s[i] == '(') {
27+
stack.add(i);
28+
} else {
29+
if (stack.isNotEmpty) stack.removeLast();
30+
31+
if (stack.isNotEmpty) {
32+
longest = max(longest, i - stack.last);
33+
} else {
34+
stack.add(i);
35+
}
36+
}
37+
}
38+
39+
return longest;
40+
}

0 commit comments

Comments
(0)

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