32. Longest Valid Parentheses

Two-pass Scan (T2R & R2T)

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
class Solution {
public int longestValidParentheses(String s) {
if (s.length() < 2) return 0;

int maxLen = 0;
int leftCount = 0, rightCount = 0;

// left to right
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
leftCount++;
} else {
rightCount++;
}

if (leftCount == rightCount) {
maxLen = Math.max(maxLen, 2 * rightCount);
} else if (rightCount > leftCount) {
// reset
leftCount = 0;
rightCount = 0;
}
}

// reset
leftCount = 0;
rightCount = 0;

// right to left
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
if (c == '(') {
leftCount++;
} else {
rightCount++;
}

if (leftCount == rightCount) {
maxLen = Math.max(maxLen, 2 * leftCount);
} else if (leftCount > rightCount) {
// reset
leftCount = 0;
rightCount = 0;
}
}

return maxLen;
}
}

Remarks:

  1. TC: $O(2n)$ or $O(n)$, SC: $O(1)$

  2. Why Two pass?

    Example: ((), left to right: 0, right to left: 1*2

  3. L2R: left should always be equal or more than right parenthesis; R2L: right should always be equal or more than left parenthesis.

Stack

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
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
stack.push(-1); // base
int maxLen = 0;

for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stack.push(i);
} else {
stack.pop(); // try to match the parenthesis

if (stack.isEmpty()) {
stack.push(i); // update the base
} else {
maxLen = Math.max(maxLen, i - stack.peek()); // check the index of the previous `)`
}
}
}

return maxLen;
}
}

Remarks:

  1. TC: $O(n)$, SC: $O(n)$

Dynamic Programming

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
class Solution {
public int longestValidParentheses(String s) {
int n = s.length();
if (n < 2) return 0;

int[] dp = new int[n];
int maxLen = 0;

for (int i = 1; i < n; i++) {
if (s.charAt(i) == ')') {
if (s.charAt(i - 1) == '(') {
dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
} else if (i - dp[i - 1] - 1 >= 0 &&
s.charAt(i - dp[i - 1] - 1) == '(') {
dp[i] = dp[i - 1] + 2 +
(i - dp[i - 1] - 2 >= 0 ? dp[i - dp[i - 1] - 2] : 0);
}

maxLen = Math.max(maxLen, dp[i]);
}
}

return maxLen;
}
}

Remarks:

  1. Base: dp[0]=0

  2. if s[i] == ')' and last one s[i-1]=='(' then dp[i] = dp[i-2] + 2

  3. if s[i] == ')' and last one s[i-1]==')' then check s[i - dp[i-1] - 1],

    dp[i] = dp[i-1] + 2 + dp[i- dp[i-1] -2]