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

Appearance settings

Latest commit

 

History

History
History
55 lines (46 loc) · 1.69 KB

File metadata and controls

55 lines (46 loc) · 1.69 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package Algorithms.string;
import java.util.Stack;
public class LongestValidParentheses {
public static void main(String[] strs) {
System.out.println(longestValidParentheses("(()()())"));
}
public int longestValidParentheses(String s) {
if (s == null) {
return 0;
}
Stack<Integer> stk = new Stack<Integer>();
int sum = 0;
int tmp = 0;
int max = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stk.push(i);
} else {
if (stk.isEmpty()) {
// 栈中没有'(',出现')', 则必须重置计算
sum = 0;
continue;
}
// count the temporary lenght:
// like: (()()()
// tmp = 2.
tmp = i - stk.pop() + 1;
if (stk.isEmpty()) {
// 有一套完整的括号集,可以加到前面的一整套括号集上
// () (()())
// 1 2 第二套括号集可以加过来
sum += tmp;
max = Math.max(sum, max);
} else {
// 也可能是一个未完成的括号集,比如:
// () (()() 在这里 ()() 是一个未完成的括号集,可以独立出来计算,作为
// 阶段性的结果
tmp = i - stk.peek();
max = Math.max(tmp, max);
}
}
}
return max;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.