【leetcode刷题笔记】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.



题解:dp+栈

用一个栈记录左括号的索引,每次匹配到")"的时候,弹出对应的左括号,并且用这个索引计算括号的长度。

用currentMax记录当前最长的匹配串,它可以由多个有效的匹配累加而成,比如"()(())",currentMax = 2 + 4 = 6;或者等于当前最大的匹配,比如"()((())",currentMax = 4;

leftLen表示匹配当前")"时,得到的最长匹配是多少,比如"()(())",leftLen = 4;

totalMax是最终最长的匹配长度,每次匹配到")"的时候更新。

遇到‘(‘,压栈

遇到‘)‘有三种情况:

  • 类似"())"或者")"的情况,即这个右括号是多余的,判断的条件是此时栈为空,说明重新开始了,把currentMax置零;
  • 类似"()()"或者"()(())"的情况,即这个右括号是匹配的,并且它匹配以后栈空了,说明前面搜索到的"()"可以和当前搜索完的串"()"或者"(())"合并起来,把currentMax += i - leftLen;
  • 类似"(()"或者"()(()",即这个右括号是匹配的,但是匹配后栈里面还有左括号,需要继续匹配,此时说明前面搜索到的"()"还不能和当前的"()"合并(二者中间有未匹配的左括号)。所以leftLen就是此时能得到的最大匹配长度了。

代码如下:

 1 public class Solution {
 2     public int longestValidParentheses(String s) {
 3         if(s==null || s.length() == 0)
 4             return 0;
 5
 6         Stack<Integer> stack = new Stack <Integer>();
 7         int totalMax = 0;
 8         int currentMax = 0;
 9
10         for(int i = 0;i < s.length();i++){
11             if(s.charAt(i) == ‘(‘){
12                 stack.push(i);
13             }
14             else{
15                 //situations like ")" or "())"
16                 if(stack.isEmpty()){
17                     currentMax = 0;
18                 }
19                 else{
20                     int leftPos = stack.pop();
21                     int leftLen = i - leftPos + 1;
22
23                    //situations like "()" or "()()",then we can accumulate with parathesis before
24                     if(stack.isEmpty()){
25                         currentMax += leftLen;
26                         leftLen = currentMax;
27                     }
28                    //situations like "(()" or "(()()",there is still left parathesis, so we can‘t accumulate
29                     else {
30                         leftLen = i - stack.peek();
31                     }
32                     totalMax = Math.max(totalMax, leftLen);
33
34                 }
35             }
36
37         }
38
39         return totalMax;
40     }
41 }

【leetcode刷题笔记】Longest Valid Parentheses

时间: 2024-11-07 14:58:18

【leetcode刷题笔记】Longest Valid Parentheses的相关文章

【leetcode刷题笔记】Valid Number

Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => true"abc" => false"1 a" => false"2e10" => true 题解:题目不难,就是有点麻烦,要注意的地方很多,总结一下: 前面和后面的空格要用s.trim()去掉: 前导的'+'和'-'号需要忽略:

刷题32. Longest Valid Parentheses

一.题目说明 题目是32. Longest Valid Parentheses,求最大匹配的括号长度.题目的难度是Hard 二.我的做题方法 简单理解了一下,用栈就可以实现.实际上是我考虑简单了,经过5次提交终于正确了. 性能如下: Runtime: 8 ms, faster than 61.76% of C++ online submissions for Longest Valid Parentheses. Memory Usage: 9.8 MB, less than 10.71% of

【leetcode刷题笔记】Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. A partially filled sudoku which is valid. Note:A valid Sudoku board (partially

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings. 题解:以strs[0]为模板,每次挨个查看是否所有的串里面是否第i位上都和strs[0]一样,如果都一样,把i位置上的字符放到answer里面,i++,继续循环,否则返回当前的answer. 代码如下: 1 public class Solution { 2 public String longestCommonPrefix

【leetcode刷题笔记】Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest subst

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys

【leetcode刷题笔记】Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. 题解:递归.在每个空位