package com.fishercoder.solutions;

import java.util.Stack;

/**
 * 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.
 */
public class _32 {
	public int longestValidParentheses(String s) {
		int result = 0;
		Stack<Integer> stack = new Stack();
		stack.push(-1);
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '(') {
				stack.push(i);
			} else {
				stack.pop();
				if (stack.isEmpty()) {
					stack.push(i);
				} else {
					result = Math.max(result, i - stack.peek());
				}
			}
		}
		return result;
	}
}

@@ -58,16 +58,52 @@
 k;%0A%0A/**%0A
+ * 32. Longest Valid Parentheses%0A *%0A
  * Given
@@ -230,17 +230,18 @@
 string.%0A
-%0A
+ *
  For %22((
@@ -315,17 +315,18 @@
 th = 2.%0A
-%0A
+ *
  Another
@@ -449,17 +449,54 @@
 s _32 %7B%0A
-%09
+  public static class Solution1 %7B%0A    
 public i
@@ -534,18 +534,22 @@
 ng s) %7B%0A
-%09%09
+      
 int resu
@@ -556,18 +556,22 @@
 lt = 0;%0A
-%09%09
+      
 Stack%3CIn
@@ -598,18 +598,22 @@
 tack();%0A
-%09%09
+      
 stack.pu
@@ -620,18 +620,22 @@
 sh(-1);%0A
-%09%09
+      
 for (int
@@ -665,19 +665,24 @@
  i++) %7B%0A
-%09%09%09
+        
 if (s.ch
@@ -699,20 +699,26 @@
  '(') %7B%0A
-%09%09%09%09
+          
 stack.pu
@@ -724,19 +724,24 @@
 ush(i);%0A
-%09%09%09
+        
 %7D else %7B
@@ -741,20 +741,26 @@
  else %7B%0A
-%09%09%09%09
+          
 stack.po
@@ -764,20 +764,26 @@
 .pop();%0A
-%09%09%09%09
+          
 if (stac
@@ -797,21 +797,28 @@
 ty()) %7B%0A
-%09%09%09%09%09
+            
 stack.pu
@@ -828,26 +828,39 @@
 i);%0A
-%09%09%09%09%7D else %7B%0A%09%09%09%09%09
+          %7D else %7B%0A            
 resu
@@ -904,25 +904,44 @@
 ));%0A
-%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D%0A%09%09
+          %7D%0A        %7D%0A      %7D%0A      
 retu
@@ -955,9 +955,16 @@
 lt;%0A
-%09
+    %7D%0A  
 %7D%0A%7D%0A

refactor 32