当前位置:网站首页>Leetcode32 longest valid bracket (dynamic programming difficult problem)
Leetcode32 longest valid bracket (dynamic programming difficult problem)
2022-07-06 03:59:00 【ajdhfla】
Give you one that only contains '(' and ')' String , Find the longest effective ( The format is correct and continuous ) The length of the bracket substring .
Example 1:
Input :s = "(()"
Output :2
explain : The longest valid bracket substring is "()"
Example 2:
Input :s = ")()())"
Output :4
explain : The longest valid bracket substring is "()()"
Example 3:
Input :s = ""
Output :0
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/longest-valid-parentheses
One : Violence solution ( Easy to understand but with high time complexity )
The easiest way to think about this problem is to find the length of the longest valid bracket substring ending in each character in the string , When I think of this, I think of using dynamic programming , But the state transition equation of this problem is not well determined , I will write the solution of dynamic programming below . The simplest way to find the longest substring ending in each character is to solve it violently through the stack , The specific method is to traverse forward from the current character , Until it doesn't meet the conditions .
Here are a few things to pay attention to :
1. Because this is traversal from back to front , So what is different from usual is that when you encounter the right parenthesis, it will be put on the stack , Stack when encountering the left bracket ;
2. How to determine the conditions for breaking the cycle : When the stack is empty and the next character in the stack is ‘(' when ;
3. In the general question of judging whether it is valid , If the stack is not empty after traversal, it is directly determined that it is invalid , But this problem may happen :"))()", If you traverse forward from the last character , It is partly effective , So how to exclude the invalid part in the front . I set up a temp Variable , Except at the beginning, if the stack is empty, it indicates that there is already a set of valid parentheses , At this point through tmep To record its length . Then continue to traverse forward , Because there may be valid parentheses after it , When the stack is not empty at the end of traversal, it will return directly temp, That is, the previous valid part .
class Solution {
public int longestValidParentheses(String s) {
if (s.length() == 0) return 0;
int ans = 0;
int[] dp = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
}
return ans;
}
public int a (String s, int x) {
Deque<Character> stack = new LinkedList<>();
int res = 0;
int temp = 0;
for (int i = x; i >= 0; --i) {
if (stack.isEmpty() && i != s.length() - 1 && s.charAt(i + 1) == '(') temp = res;
if (stack.isEmpty() && s.charAt(i) == '(') break;
else if (s.charAt(i) == ')') stack.addLast(s.charAt(i));
else if (s.charAt(i) == '(') {
stack.pollLast();
}
res++;
}
if(!stack.isEmpty()) return temp;
return res;
}
}Two : Dynamic programming
The key of dynamic programming is to determine the state transition equation , The same idea as above requires the length of the longest valid bracket substring ending in each character in the string , And recorded in the array dp[] in , The idea is as follows :
Traversal string
1. If the current character is '(' when , Cannot form a valid bracket substring that ends with the current character ;
2. If the current character is ')' when :
2.1 i-1 The character of the position is ’(', At this time, this character forms a valid bracket with the previous character , Directly to dp[i-2]+2 that will do , But consider i-2 Is it greater than 0;
2.2 i-1 The character of the position is ')', At this point, if you want to form a valid string "..(.....))" The following conditions must be met :
1.dp[i - 1] Greater than 0, Because the middle of these two brackets must also be valid brackets , A set of parentheses outside a set of invalid parentheses is also invalid ;
2.i - dp[i - 1] - 1 Greater than or equal to zero ,i - dp[i - 1] - 1 namely i The position of the corresponding left parenthesis ;
3. The position of the corresponding left bracket should be '(' Otherwise, invalid parentheses ;
4. After meeting the above conditions , It can be judged that dp[i] Greater than or equal to dp[i - 1] + 2, Because this may happen :"()(())", In this example, when dp[5]=2,dp[6]=6, This is because after connecting the left bracket of the corresponding position , If there are valid parentheses on the left of the left parenthesis, they should be counted together .
class Solution {
public int longestValidParentheses(String s) {
int ans = 0;
int[] dp = new int[s.length()];
for (int i = 1; i < s.length(); i++){
if (s.charAt(i) == ')') {
if (s.charAt(i - 1) == '(') {
if (i >= 2) dp[i] = dp[i - 2] + 2;
else dp[i] = 2;
}else if (i - dp[i - 1] - 1>= 0 > 0 && s.charAt(i - dp[i - 1] - 1) == '(') {
dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;
}
ans = ans > dp[i] ? ans : dp[i];
}
}
return ans;
}
}
边栏推荐
- Blue Bridge Cup - Castle formula
- Image super resolution using deep revolutionary networks (srcnn) interpretation and Implementation
- 【按鍵消抖】基於FPGA的按鍵消抖模塊開發
- C#(二十七)之C#窗体应用
- [FPGA tutorial case 12] design and implementation of complex multiplier based on vivado core
- C form application of C (27)
- Blue style mall website footer code
- C mouse event and keyboard event of C (XXVIII)
- TCP/IP协议里面的网关地址和ip地址有什么区别?
- Microkernel structure understanding
猜你喜欢

Stack and queue
![[analysis of variance] single factor analysis and multi factor analysis](/img/92/5337d0ef6e487d1af2f56cb3a3268a.jpg)
[analysis of variance] single factor analysis and multi factor analysis

自动化测试的好处
![[adjustable delay network] development of FPGA based adjustable delay network system Verilog](/img/82/7ff7f99f5164f91fab7713978cf720.png)
[adjustable delay network] development of FPGA based adjustable delay network system Verilog

Record the pit of NETCORE's memory surge

Recommended papers on remote sensing image super-resolution

TCP/IP协议里面的网关地址和ip地址有什么区别?

C language circular statement

How to standardize the deployment of automated testing?

STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
随机推荐
[adjustable delay network] development of FPGA based adjustable delay network system Verilog
Network security - Security Service Engineer - detailed summary of skill manual (it is recommended to learn and collect)
Schnuka: what is visual positioning system and how to position it
/usr/bin/gzip: 1: ELF: not found/usr/bin/gzip: 3: : not found/usr/bin/gzip: 4: Syntax error:
[practice] mathematics in lottery
Ks003 mall system based on JSP and Servlet
Cf603e pastoral oddities [CDQ divide and conquer, revocable and search set]
Security xxE vulnerability recurrence (XXe Lab)
51nod 1130 n factorial length V2 (Stirling approximation)
math_极限&微分&导数&微商/对数函数的导函数推导(导数定义极限法)/指数函数求导公式推导(反函数求导法则/对数求导法)
[FPGA tutorial case 11] design and implementation of divider based on vivado core
记一次excel XXE漏洞
How do we make money in agriculture, rural areas and farmers? 100% for reference
80% of the diseases are caused by bad living habits. There are eight common bad habits, which are both physical and mental
Determine which week of the month the day is
Tips for using dm8huge table
[American competition] mathematical terms
Ipv4中的A 、B、C类网络及子网掩码
C (thirty) C combobox listview TreeView
Yyds dry goods inventory web components series (VII) -- life cycle of custom components