forked from licong1112/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestValidParentheses.java
56 lines (50 loc) · 1.68 KB
/
LongestValidParentheses.java
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
/**
* Practiced on 12/8/2012
*
* Given a string containing just the characters '(' and ')', find the length of the
* longest valid (well-formed) parentheses substring.
*
* For "(()", the longest valid parentheses substring is "()", which has length = 2.
*
* Another example is ")()())", where the longest valid parentheses substring is "()()",
* which has length = 4.
*
* ======================================
* Below is an implementation of O(n) algorithm. A clearer way to implement it is to build
* a class with char and its corresponding index. Then we only need one stack.
*/
package com.congli.leetcode;
import java.util.Stack;
public class LongestValidParentheses {
public int longestValidParentheses(String s)
{
Stack<Character> stackChar = new Stack<Character>();
Stack<Integer> stackIndex = new Stack<Integer>();
int result = 0;
for(int i = 0; i < s.length(); ++i)
{
char currChar = s.charAt(i);
if(currChar == '(')
{
stackChar.push(currChar);
stackIndex.push(i);
}
else
{
if(!stackChar.isEmpty() && stackChar.peek() == '(')
{
stackChar.pop();
stackIndex.pop();
int length = stackChar.isEmpty() ? (i+1) : (i-stackIndex.peek());
result = length > result ? length : result;
}
else
{
stackChar.push(currChar);
stackIndex.push(i);
}
}
}
return result;
}
}