描述
给出一个长度为 n 的,仅包含字符 '(' 和 ')' 的字符串,计算最长的格式正确的括号子串的长度。
题目解法:使用栈结构对问题进行求解
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return int整型
*/
public int longestValidParentheses (String s) {
// write code here
Stack<Integer> stack=new Stack();
stack.push(-1);
int ans=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='(')
{
stack.push(i);
}
if(s.charAt(i)==')')
{
stack.pop();
if(stack.isEmpty()){
stack.push(i);
}
else{
ans=Math.max(ans,i-stack.peek());
}
}
}
return ans;
}
}