Created
June 17, 2013 15:58
-
-
Save daifu/5798016 to your computer and use it in GitHub Desktop.
Longest Valid Parentheses - Leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 Solution { | |
public int longestValidParentheses(String s) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(s.length() == 0) return 0; | |
int curMax = 0; | |
int absMax = 0; | |
Stack<Character> stack = new Stack<Character>(); | |
for(int i = 0; i < s.length(); i++) { | |
if(s.charAt(i) == '(') { | |
stack.push('('); | |
} else { | |
if(stack.size() > 0) { | |
stack.pop(); | |
curMax+=2; | |
} | |
if(curMax > absMax) { | |
absMax = curMax; | |
if(stack.size() == 0 && i < (s.length()-1) && s.charAt(i+1) == ')') | |
curMax = 0; | |
} | |
} | |
} | |
return absMax; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment