题目描述:
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 Longest_Valid_Parentheses {
public static int longestValidParentheses(String s)
{
char str[] = s.toCharArray();
//保存'('.
Stack<Integer> stack = new Stack<Integer>();
//保存间断点.
ArrayList<Integer> breakList = new ArrayList<Integer>();
int count = 0;
for(int i=0;i<s.length();i++)
{
if(str[i]=='(')
{
stack.push(i);
}
else
{
if(!stack.isEmpty())
{
stack.pop();
}
else
{
breakList.add(i);
}
}
}
//合并'('和')'间断点
while(!stack.isEmpty())
{
breakList.add(stack.pop());
}
if(!breakList.isEmpty())
{
int breakArray[] = new int[breakList.size()];
for(int i=0;i<breakList.size();i++)
{
breakArray[i] = breakList.get(i);
}
Arrays.sort(breakArray);
for(int i=0;i<breakArray.length-1;i++)
{
int diff = breakArray[i+1]-breakArray[i]-1;
count = Math.max(count,diff);
}
count = Math.max(count,breakArray[0]);
count = Math.max(count,s.length()-breakArray[breakArray.length-1]-1);
}
else
{
return s.length();
}
return count;
}
public static void main(String[] args) {
String s = "(()";
System.out.println(longestValidParentheses(s));
}
}
在网上还看到一种更简洁的写法:
public int longestValidParentheses(String s) {
if(s==null || s.length()==0)
return 0;
LinkedList<Integer> stack = new LinkedList<Integer>();
int start = 0;
int max = 0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='(')
{
stack.push(i);
}
else
{
if(stack.isEmpty())
{
start = i+1;
}
else
{
stack.pop();
max = stack.isEmpty()?Math.max(max,i-start+1):Math.max(max,i-stack.peek());
}
}
}
return max;
}
意思一样,只不过第二种处理更加巧妙。