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 f306cb3

Browse files
add q32
1 parent 962f808 commit f306cb3

File tree

3 files changed

+72
-46
lines changed

3 files changed

+72
-46
lines changed

‎.idea/workspace.xml‎

Lines changed: 33 additions & 46 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
### 栈相关
5959

6060
* [q20_有效的括号](/src/栈相关/q20_有效的括号)
61+
* [q32_最长有效括号](/src/栈相关/q32_最长有效括号)
6162
* [q224_基本计算器](/src/栈相关/q224_基本计算器)
6263
* [q316_去除重复字母](/src/栈相关/q316_去除重复字母)
6364

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package 栈相关.q32_最长有效括号;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* 利用索引栈 o(n)
7+
*/
8+
public class Solution {
9+
10+
public int longestValidParentheses(String s) {
11+
if (s == null || s.length() < 2) {
12+
return 0;
13+
}
14+
15+
int maxLen = 0;
16+
Stack<Integer> stack = new Stack<>();
17+
stack.push(-1);
18+
for (int i = 0; i < s.length(); i++) {
19+
char temp = s.charAt(i);
20+
if (temp == '(') {
21+
stack.push(i);
22+
} else {
23+
stack.pop();
24+
if (stack.empty()) {
25+
stack.push(i);
26+
} else {
27+
maxLen = Math.max(maxLen, i - stack.peek());
28+
}
29+
}
30+
}
31+
32+
return maxLen;
33+
}
34+
35+
public static void main(String[] args) {
36+
System.out.println(new Solution().longestValidParentheses(")()())"));
37+
}
38+
}

0 commit comments

Comments
(0)

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