Skip to content

Commit c71f3bb

Browse files
Longest Valid Parentheses
1 parent d6f9d93 commit c71f3bb

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,7 @@ My accepted leetcode solutions to some of the common interview problems.
250250
- [Exclusive Time of Functions](problems/src/stack/ExclusiveTimeOfFunctions.java) (Medium)
251251
- [Basic Calculator](problems/src/stack/BasicCalculator.java) (Hard)
252252
- [Decode String](problems/src/stack/DecodeString.java) (Medium)
253+
- [Longest Valid Parentheses](problems/src/stack/LongestValidParentheses.java) (Hard)
253254

254255

255256
#### [String](problems/src/string)
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package stack;
2+
3+
import java.util.*;
4+
5+
/**
6+
* Created by gouthamvidyapradhan on 08/07/2018.
7+
* Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed)
8+
* parentheses substring.
9+
10+
Example 1:
11+
12+
Input: "(()"
13+
Output: 2
14+
Explanation: The longest valid parentheses substring is "()"
15+
Example 2:
16+
17+
Input: ")()())"
18+
Output: 4
19+
Explanation: The longest valid parentheses substring is "()()"
20+
21+
Solution: O(N) Iterate through each of the parentheses and if '(' is encountered push it to stack else check the top
22+
of the stack to see if there is a matching parentheses, if yes pop it and then take the length (currIndex - index at
23+
top of the stack). Maintain a max length and return this as the answer.
24+
*/
25+
public class LongestValidParentheses {
26+
27+
private class Node{
28+
char c;
29+
int i;
30+
Node(char c, int i){
31+
this.c = c;
32+
this.i = i;
33+
}
34+
}
35+
36+
/**
37+
*
38+
* @param args
39+
* @throws Exception
40+
*/
41+
public static void main(String[] args) throws Exception{
42+
System.out.println(new LongestValidParentheses().longestValidParentheses("((()()(((())))))"));
43+
}
44+
45+
public int longestValidParentheses(String s) {
46+
Stack<Node> stack = new Stack<>();
47+
int max = 0;
48+
for(int i = 0, l = s.length(); i < l; i ++){
49+
char c = s.charAt(i);
50+
switch (c){
51+
case '(':
52+
stack.push(new Node(c, i));
53+
break;
54+
55+
case ')':
56+
if(!stack.isEmpty()){
57+
if(stack.peek().c == '('){
58+
stack.pop();
59+
if(stack.isEmpty()){
60+
max = Math.max(max, i + 1);
61+
} else {
62+
max = Math.max(max, i - stack.peek().i);
63+
}
64+
} else{
65+
stack.push(new Node(c, i));
66+
}
67+
} else{
68+
stack.push(new Node(c, i));
69+
}
70+
}
71+
}
72+
return max;
73+
}
74+
75+
}

0 commit comments

Comments
 (0)