Skip to content

Commit 6649edb

Browse files
committed
LongestValidParentheses
1 parent 1ab5e14 commit 6649edb

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package popular;
2+
3+
import java.util.Stack;
4+
5+
public class LongestValidParentheses {
6+
7+
/**
8+
* 用Stack存储开始匹配的上一个位置,那么当前的位置减去上个位置,就是最长的匹配,
9+
* 时间复杂度为O(n), 空间复杂度为O(n)
10+
* @param s
11+
* @return
12+
*/
13+
public int longestValidParentheses(String s) {
14+
int len = s.length();
15+
Stack<Integer> stack = new Stack<>();
16+
stack.push(-1);
17+
int maxLen = 0;
18+
for (int i = 0; i < len; i++) {
19+
if (s.charAt(i) == '(') {
20+
stack.push(i);
21+
} else {
22+
stack.pop();
23+
if (stack.isEmpty()) {
24+
stack.push(i);
25+
} else {
26+
maxLen = Math.max(maxLen, i - stack.peek());
27+
}
28+
}
29+
}
30+
31+
return maxLen;
32+
}
33+
34+
35+
/**
36+
* 从左到右,又从右到左,两个方向找最长的匹配。
37+
* 时间复杂度为O(n), 空间复杂度为O(1)
38+
* @param s
39+
* @return
40+
*/
41+
public int longestValidParenthesesWithoutStack(String s) {
42+
int left = 0;
43+
int right = 0;
44+
int maxLen = 0;
45+
int len = s.length();
46+
for (char c: s.toCharArray()) {
47+
if (c == '(') {
48+
left++;
49+
} else {
50+
right++;
51+
}
52+
if (left == right) {
53+
maxLen = Math.max(maxLen, right * 2);
54+
} else if (right > left) {
55+
left = right = 0;
56+
}
57+
}
58+
59+
left = right = 0;
60+
for (int i = len - 1; i >= 0; i--) {
61+
if (s.charAt(i) == '(') {
62+
left++;
63+
} else {
64+
right++;
65+
}
66+
if (left == right) {
67+
maxLen = Math.max(maxLen, left * 2);
68+
} else if (left > right) {
69+
left = right = 0;
70+
}
71+
}
72+
73+
return maxLen;
74+
}
75+
76+
public static void main(String[] args) {
77+
String input = "((())";
78+
LongestValidParentheses obj = new LongestValidParentheses();
79+
//System.out.println("input: ((()), Output -> " + obj.longestValidParentheses(input));
80+
System.out.println("input: ((()), Output -> " + obj.longestValidParenthesesWithoutStack(input));
81+
}
82+
}

0 commit comments

Comments
 (0)