# Longest Valid Parentheses

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) {
Stack<int[]> record = new Stack<>();
int max = 0;
for(int i = 0; i < s.length(); i++){
int currentSymbol = s.charAt(i) == '('? 1 : 2;
if(currentSymbol == 1){
record.push(i * 10 + 1);
}
else{
if(record.empty() || record.peek() % 10 == 2)
record.push(i * 10 + 2);
else{
record.pop();
int localLength = 0;
if(record.empty()){
localLength = i + 1;
}
else{
localLength = i - record.peek() / 10;
}

max = Math.max(max, localLength);
}
}
}
return max;
}
}

• 本文已收录于以下专栏：

## Leetcode Algorithm 032. Longest Valid Parentheses

Leetcode Algorithm 032. Longest Valid Parentheses 给定一个只含有'('和')'的字符串，求出符合括号匹配要求的最长子串（不是子序列）。...

## leetcode-32. Longest Valid Parentheses

leetcode-32. Longest Valid Parentheses - 如果是左括号就将当前位置压人栈， - 如果是右括号就判断当前栈是否为空， - 如果是空则说明之前数据违法...

## leetcode 32 -- Longest Valid Parentheses

Longest Valid Parentheses 题目： Given a string containing just the characters ‘(’ and ‘)’, find t...

## [LeetCOde32]Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (we...
• sbitswc
• 2014年06月15日 00:17
• 595

## LeetCode - Longest Valid Parentheses

https://leetcode.com/problems/longest-valid-parentheses/ Given a string containing just the cha...

## leetcode 32. Longest Valid Parentheses——（use stack）

import java.util.Stack; //Given a string containing just the characters '(' and ')', find the lengt...

## Leetcode32:Longest Valid Parentheses

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (wel...

举报原因： 您举报文章：Longest Valid Parentheses 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)