标签:style blog color os io for re c
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.
题解:dp+栈
用一个栈记录左括号的索引,每次匹配到")"的时候,弹出对应的左括号,并且用这个索引计算括号的长度。
用currentMax记录当前最长的匹配串,它可以由多个有效的匹配累加而成,比如"()(())",currentMax = 2 + 4 = 6;或者等于当前最大的匹配,比如"()((())",currentMax = 4;
leftLen表示匹配当前")"时,得到的最长匹配是多少,比如"()(())",leftLen = 4;
totalMax是最终最长的匹配长度,每次匹配到")"的时候更新。
遇到‘(‘,压栈
遇到‘)‘有三种情况:
代码如下:
1 public class Solution { 2 public int longestValidParentheses(String s) { 3 if(s==null || s.length() == 0) 4 return 0; 5 6 Stack<Integer> stack = new Stack <Integer>(); 7 int totalMax = 0; 8 int currentMax = 0; 9 10 for(int i = 0;i < s.length();i++){ 11 if(s.charAt(i) == ‘(‘){ 12 stack.push(i); 13 } 14 else{ 15 //situations like ")" or "())" 16 if(stack.isEmpty()){ 17 currentMax = 0; 18 } 19 else{ 20 int leftPos = stack.pop(); 21 int leftLen = i - leftPos + 1; 22 23 //situations like "()" or "()()",then we can accumulate with parathesis before 24 if(stack.isEmpty()){ 25 currentMax += leftLen; 26 leftLen = currentMax; 27 } 28 //situations like "(()" or "(()()",there is still left parathesis, so we can‘t accumulate 29 else { 30 leftLen = i - stack.peek(); 31 } 32 totalMax = Math.max(totalMax, leftLen); 33 34 } 35 } 36 37 } 38 39 return totalMax; 40 } 41 }
【leetcode刷题笔记】Longest Valid Parentheses,布布扣,bubuko.com
【leetcode刷题笔记】Longest Valid Parentheses
标签:style blog color os io for re c
原文地址:http://www.cnblogs.com/sunshineatnoon/p/3865249.html