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.
Subscribe to see which companies asked this question
package cc.stack.application;
import java.util.Stack;
/*
* 字符串遍歷,遇"("入棧,遇")"且棧頂是"(",ok一次
*/
class Solution {
public int longestValidParentheses(String s) {
if(s == null || s.length() == 0)
return 0;
Stack<String> stack = new Stack<String>();
int result = 0;
for(int i=0; i<s.length(); i++) {
if(s.substring(i, i+1).equals("("))
stack.push(s.substring(i, i+1));
else if(s.substring(i, i+1).equals(")")) {
if(!stack.isEmpty()) {
if(stack.pop().equals("("))
result++;
}
}
}
return result*2;
}
}
public class Main1 {
public static void main(String[] args) {
Solution s = new Solution();
String tokens = "( ) ( ( ( ) )";
System.out.println(s.longestValidParentheses(tokens));
}
}