-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32.longest-valid-parentheses.java
More file actions
77 lines (67 loc) · 1.56 KB
/
32.longest-valid-parentheses.java
File metadata and controls
77 lines (67 loc) · 1.56 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.Stack;
/*
* @lc app=leetcode id=32 lang=java
*
* [32] Longest Valid Parentheses
*
* https://leetcode.com/problems/longest-valid-parentheses/description/
*
* algorithms
* Hard (26.54%)
* Likes: 2574
* Dislikes: 112
* Total Accepted: 235.9K
* Total Submissions: 876.1K
* Testcase Example: '"(()"'
*
* Given a string containing just the characters '(' and ')', find the length
* of the longest valid (well-formed) parentheses substring.
*
* Example 1:
*
*
* Input: "(()"
* Output: 2
* Explanation: The longest valid parentheses substring is "()"
*
*
* Example 2:
*
*
* Input: ")()())"
* Output: 4
* Explanation: The longest valid parentheses substring is "()()"
*
*
*/
/**
* one method is to use stack
*/
// @lc code=start
class Solution {
public int longestValidParentheses(String s) {
if (s == null) {
return 0;
}
Stack<Integer> tmp = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!tmp.isEmpty() && (c==')'&& s.charAt(tmp.peek())=='(')) {
tmp.pop();
} else {
tmp.push(i);
}
}
//go through the index in stack to find the longest valid parentheses
int max = 0;
int current = s.length();
while (!tmp.isEmpty()) {
int index = tmp.pop();
max = Math.max(max, current-index-1);
current = index;
}
max = Math.max(max, current);
return max;
}
}
// @lc code=end