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 are the 2 ways how I implemented it.
For getMaxParentheses2(), it always stores element into stack. When there is a pop function, it will calculate the size by curr_pos and peek() for the length.
For getMaxParentheses(), it only stores legal parentheses in stack. In this way, it uses start variable to store the legal parentheses start position. When there is a pop function and stack is empty, it will use curr_pos-start to get the length, or it will still use curr_pos and peek() for the length.
public static int getLongestParentheses(char[] chs) { if(chs==null||chs.length==0) { return 0; } int maxSize = 0; int start = 0; Stack stack = new Stack(); for(int i=0; ilength; i++) { if(chs[i]=='(') { stack.push(i); } else if(stack.empty()) { start = i + 1; } else { stack.pop(); maxSize = stack.isEmpty() ? Math.max(maxSize, i-start+1) : Math.max(maxSize, i-stack.peek()); } } return maxSize; } public static int getMaxParentheses2(char[] chs) { Stack stack = new Stack(); int max = Integer.MIN_VALUE; for(int i=0; ilength; i++) { if(stack.isEmpty() || chs[i]=='(' || chs[stack.peek()]==')') { stack.push(i); } else { stack.pop(); int currMax = stack.isEmpty() ? i+1 : i-stack.peek(); max = currMax > max ? currMax : max; } } return max; }
Check my code on github: link
Besides, this problem also can be solved by dp. Here is from junmin’s solution: link