leetcode32.最长有效括号(栈)

给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。

 

示例 1:

输入:s = "(()"
输出:2
解释:最长有效括号子串是 "()"
示例 2:

输入:s = ")()())"
输出:4
解释:最长有效括号子串是 "()()"
示例 3:

输入:s = ""
输出:0

 

 

解题思路:依然可以使用辅助栈来解决问题

 1 class Solution{
 2 public int longestValidParentheses(String s ){
 3 LinkedList<Integer> stack = new LinkedList<Integer>();
 4 int res = 0;
 5 for(int i = 0; i < s.length();i++){
 6 if(stack.isEmpty() || s.chatAt(i) == "(" || s.chatAt(stack.getLast()) ==")"){
 7 stack.addLast(i);
 8 }else{
 9 srack.removeLast();
10 res = Math.max(res,stack.isEmpty ?  i + 1 : i - stack.getLast());
11 }
12 }
13 return res;
14 }
15 }

 

posted @ 2021-09-04 22:40  LeoLxx  阅读(43)  评论(0编辑  收藏  举报