The idea is to loop the String, and create an array to save the current length by each of the char inside the String. As the solute below, in order to get the current length, it relies on the result of n-2 as well, which contains information from (n-2)-2, in this way retrieve the longest length. Notice that the result will be max(max, index - right[index] + 2)
public class Solution {
public int longestValidParentheses(String s) {
if(s == null || s.length() < 2){
return 0;
}
int[] right = new int[s.length()];
int max = 0;
Stack<Integer> process = new Stack<Integer>();
int index = 0;
while(index < s.length()){
if(s.charAt(index) == '('){
process.push(index);
}else{
if(!process.isEmpty()){
right[index] = process.pop() + 1;
int temp = right[index] - 2;
if(temp >= 0 && right[temp] > 0){
right[index] = right[temp];
}
max = Math.max(index - right[index] + 2,max);
}
}
index++;
}
return max;
}
}
没有评论:
发表评论