public int longestValidParentheses(String s) {
char[] S = s.toCharArray();
int[] V = new int[S.length];
int open = 0;
int max = 0;
for (int i=0; i<S.length; i++) {
if (S[i] == '(') open++;
if (S[i] == ')' && open > 0) {
V[i] = 2 + V[i1] + (i2V[i1] > 0 ? V[i2V[i1]] : 0);
open;
}
if (V[i] > max) max = V[i];
}
return max;
}
Simple Java solution.


Dear saumeel_yogesh,
You can translate one to the other. Let's see:
V[i] = 2 + V[i1]; if(iV[i] >= 0) { V[i] += V[iV[i]]; }
From the second line you can replace every
V[i]
which is on the right side to2 + V[i1]
. So you get:V[i] = 2 + V[i1]; if(i2V[i1] >= 0) { V[i] += V[i2V[i1]]; }
And now you can rephrase it like the OP wrote:
V[i] = 2 + V[i1] + (i2V[i1] >= 0) ? V[i2V[i1]] : 0;
