[leetcode]32. Longest Valid Parentheses最长合法括号子串
Posted 程序媛詹妮弗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]32. Longest Valid Parentheses最长合法括号子串相关的知识,希望对你有一定的参考价值。
Given a string containing just the characters ‘(‘
and ‘)‘
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()"
题意:
思路:
用Stack来辅助check Valid Parentheses
用一前一后两个指针来找longest result
代码:
1 class Solution { 2 public int longestValidParentheses(String s) { 3 int result = 0; 4 int start = -1; 5 Stack<Integer> stack = new Stack<>(); // index of every char 6 for(int i = 0; i < s.length(); i++){ 7 char c = s.charAt(i); 8 if(c == ‘(‘){ 9 stack.push(i); 10 }else if( c == ‘)‘){ 11 if(stack.isEmpty()){ 12 start = i; 13 }else{ 14 stack.pop(); 15 if(stack.isEmpty()){ 16 result = Math.max(result, i - start); 17 }else{ 18 result = Math.max(result, i - stack.peek()); 19 } 20 } 21 } 22 } 23 return result; 24 } 25 }
以上是关于[leetcode]32. Longest Valid Parentheses最长合法括号子串的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]32. Longest Valid Parentheses
LeetCode 32. Longest Valid Parentheses
LeetCode 32. Longest Valid Parentheses
LeetCode 32. Longest Valid Parentheses