当前位置:网站首页>[Li Kou brush questions] 32 Longest valid bracket
[Li Kou brush questions] 32 Longest valid bracket
2022-07-06 21:20:00 【Li xiaoenzi】
Catalog
Method 1 :
subject :
Give you one that only contains '('
and ')'
String , Find the longest effective ( The format is correct and continuous ) The length of the bracket substring .
Method 1 :
Their thinking :
Utilization stack , I learned to use the stack to judge that a contains only '(' and ')' Whether the string of is parenthesized , The solution to that problem is , Traversing the entire string , If it's an open parenthesis, it's on the stack , Is the right parenthesis ① Determine whether the stack has an open bracket and pop up an open bracket ,② If the stack is empty, then false, If all characters are traversed , If there are elements in the stack, they are false, Otherwise true.
Use this idea , Add an array of tags arr, Initialize all elements to 1, What is stored in the stack is the array subscript ( Character index ). Traversing the entire string , If it is an open parenthesis, the index subscript (i) Join the stack , If it is a right parenthesis, judge whether the element in the stack is empty and if not, pop up , And mark the elements corresponding to the array arr[stack.pop()] And the tag array element corresponding to the current subscript arr[i] Set as 0.
Finally, determine the tag array arr The longest continuous 0 That's all right. .
Code :
class Solution {
public int longestValidParentheses(String s) {
// Find the longest valid bracket
// Stack
// Use the stack to mark whether the left and right parentheses are valid , The contents of the stack are stored with subscripts i
Stack<Integer> stack = new Stack<>();
int[] valid = new int[s.length()];
for(int i = 0; i < s.length(); i++){
valid[i] = 1;
}
for(int i = 0; i < s.length();i++){
if(s.charAt(i) == '(') stack.push(i);
else{
if(!stack.empty()){
valid[i] = 0;
valid[stack.pop()] = 0;
}
}
}
int res = 0,count = 0;
for(int i = 0; i < s.length();i++){
if(valid[i] == 1) {
count = 0;
}else{
count++;
}
res = Math.max(res,count);
}
return res;
}
}
Method 2 :
Their thinking :
Dynamic programming , utilize dp[i] Express By subscript i The length of the longest valid bracket at the end of the character . take dp The array is all initialized to 0. A valid substring must be in ')' ending , With '(' The ending substring corresponds to dp The value must be 0. So we just need to solve it to ')' stay dp The value of the corresponding position in the array . So go through the string from front to back , solve dp value .
①s.charAt(i)=')' And s.charAt(i-1)='(', String is "...()" be dp[i] = dp[i-2]+2.
② If s.charAt(i) = ')' And s.charAt(i-1) = ')', Like strings "...))"->"()(())",
If s.charAt(i - dp[i - 1] - 1)='(', Then the effective bracket length increases the length 2,i The longest valid bracket length of position pair is i-1 The longest bracket length of the position plus the new 2, But you have to Be careful ,i − dp[i − 1] − 1 and i Form a valid pair of parentheses , This will be a paragraph Independent valid parenthesis sequence , If the previous subsequence is shaped like (...)(...) This sequence , Then the longest valid bracket length of the current position needs to add this paragraph . for example :()(()), The red one on the left and The green one on the right Is a sequence of two independent valid parentheses . So the state transfer equation is :dp[i] = dp[i - 1] + 2 + dp[i - dp[i - 1] -2 ].
Icon :
Also note the boundary value , Because we need to use it dp[ i - 2 ], also dp[ i - dp[ i - 1 ] - 2 ], To judge .
Code :
class Solution {
public int longestValidParentheses(String s) {
// Dynamic programming
//dp[i] Denotes the following i The length of the longest valid bracket at the end of the character
int res = 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] > 0 && s.charAt(i - dp[i - 1] - 1) == '('){
if(i - dp[i - 1] >= 2) dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2;
else dp[i] = dp[i - 1] + 2;
}
}
res = Math.max(res,dp[i]);
}
return res;
}
}
Method 2: look at the analysis , Not good at writing Dynamic Planning , Next time, find an opportunity to practice the topic of Dynamic Planning .
边栏推荐
- Huawei device command
- 【Redis设计与实现】第一部分 :Redis数据结构和对象 总结
- js 根据汉字首字母排序(省份排序) 或 根据英文首字母排序——za排序 & az排序
- SDL2来源分析7:演出(SDL_RenderPresent())
- 【力扣刷题】32. 最长有效括号
- R語言可視化兩個以上的分類(類別)變量之間的關系、使用vcd包中的Mosaic函數創建馬賽克圖( Mosaic plots)、分別可視化兩個、三個、四個分類變量的關系的馬賽克圖
- Data Lake (VIII): Iceberg data storage format
- 快讯:飞书玩家大会线上举行;微信支付推出“教培服务工具箱”
- 3D face reconstruction: from basic knowledge to recognition / reconstruction methods!
- Internet News: Geely officially acquired Meizu; Intensive insulin purchase was fully implemented in 31 provinces
猜你喜欢
OneNote 深度评测:使用资源、插件、模版
No Yum source to install SPuG monitoring
966 minimum path sum
ICML 2022 | Flowformer: 任务通用的线性复杂度Transformer
Manifest of SAP ui5 framework json
[MySQL] basic use of cursor
Laravel notes - add the function of locking accounts after 5 login failures in user-defined login (improve system security)
The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix
嵌入式开发的7大原罪
Four common ways and performance comparison of ArrayList de duplication (jmh performance analysis)
随机推荐
Forward maximum matching method
Start the embedded room: system startup with limited resources
OAI 5g nr+usrp b210 installation and construction
OneNote in-depth evaluation: using resources, plug-ins, templates
Aike AI frontier promotion (7.6)
Huawei device command
【mysql】触发器
What's the best way to get TFS to output each project to its own directory?
缓存更新策略概览(Caching Strategies Overview)
Reinforcement learning - learning notes 5 | alphago
The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix
20220211 failure - maximum amount of data supported by mongodb
Le langage r visualise les relations entre plus de deux variables de classification (catégories), crée des plots Mosaiques en utilisant la fonction Mosaic dans le paquet VCD, et visualise les relation
Chris LATTNER, the father of llvm: why should we rebuild AI infrastructure software
[sliding window] group B of the 9th Landbridge cup provincial tournament: log statistics
Notes - detailed steps of training, testing and verification of yolo-v4-tiny source code
LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
R language for text mining Part4 text classification
快讯:飞书玩家大会线上举行;微信支付推出“教培服务工具箱”
3D face reconstruction: from basic knowledge to recognition / reconstruction methods!