package algorithm;
import java.util.Stack;
/*
【032-Longest Valid Parentheses(最长有效括号)】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
原题
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 LongestValidParentheses {
public static int solution(String str){
char[] chs=str.toCharArray();
int max=0;
int tmp=0;
Stack<Character> sk=new Stack<Character>();
sk.add(' ');
for(int i=0;i<chs.length;i++){
char ch=chs[i];
switch(ch){
case '(':{
//tmp++;
sk.push(ch);
break;
}
case ')':{
char ch1=sk.empty()?' ':sk.pop();//
if(ch1=='('){
tmp+=2;
if(tmp>max){ max=tmp;}
}else{
tmp=0;
}
break;
}
}
}
return max;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="(()";
str=")()())";
str="(((()))))";
int result=solution(str);
System.out.println(result);
}
}