最长连续有效括号 Longest Valid Parentheses @LeetCode

来源:互联网 发布:linux ip设置命令 编辑:程序博客网 时间:2024/05/30 07:12

思路:用栈保存左括号(


遇到(就直接压入栈中。


遇到):要用一个变量保存第一个(的下标位置firstLeftPos

如果当前栈为空,则更新firstLeftPos,然后忽略这个)。

如果栈非空,则弹栈,取出匹配的(。如果弹栈后的栈非空则根据当前)的下标和栈顶元素计算长度;如果弹栈后的栈为空,则更具当前)的下标和firstLeftPos计算长度。


package Level4;import java.util.Stack;/**Longest Valid ParenthesesGiven 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 S32 {public static void main(String[] args) {System.out.println(longestValidParentheses("(())"));System.out.println(longestValidParentheses(")("));System.out.println(longestValidParentheses("()()"));System.out.println(longestValidParentheses("(()"));}public static int longestValidParentheses(String s) {if(s.length() < 2){return 0;}Stack<Pair> stack = new Stack<Pair>();int curPos = 0;int firstLeftPos = 0;// 存放第一个 ( 的下标位置int max = 0;while(curPos < s.length()){char c = s.charAt(curPos);if(c == '('){stack.push(new Pair(c, curPos));}else{// c == ')'if(!stack.isEmpty()){// 栈非空stack.pop();// 把对应的 ( 弹出if(!stack.isEmpty()){// 弹栈后,栈内仍有元素max = Math.max(max, curPos-stack.peek().index);}else{// 弹栈后,栈空了max = Math.max(max, curPos-firstLeftPos+1);}}else{// 栈空,又遇到 ), 更新都一个(的下标位置firstLeftPos = curPos + 1;}}curPos++;// 更新当前遍历string的下标位置}return max;}// 构建一个Pair,同时存放字符和其对应下标public static class Pair{char c;int index;public Pair(char c_, int index_){c = c_;index = index_;}}}


1 0