JAVA------------Easy Version To UnderStand!!!!!!!!!!!!


  • 0
    H
    	public static int longestValidParentheses(String s) {
    	if (s == null || s.length() == 0)
    		return 0;
    	int len = s.length(), maxLen = 0;
    	Stack<Integer> stack = new Stack<>();
    	stack.push(-1);
    
    	for (int i = 0; i < len; i++) {
    		if (s.charAt(i) == '(')
    			stack.push(i);
    		else {
    			if (stack.size() > 1 && s.charAt(stack.peek()) == '(') {
    				stack.pop();
    				maxLen = Integer.max(i - stack.peek(), maxLen);
    			} else 
    				stack.push(i);
    		}
    	}
    	return maxLen;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.