当前位置:网站首页>678. Valid bracket string
678. Valid bracket string
2022-07-01 10:19:00 【hequnwang10】
One 、 Title Description
Given a string containing only three characters :( ,) and *, Write a function to check whether the string is a valid string . Valid strings have the following rules :
- Any left parenthesis ( There must be a corresponding closing bracket ).
- Any closing parenthesis ) There must be a corresponding left parenthesis ( .
- Left parenthesis ( Must precede the corresponding closing bracket ).
- Can be treated as a single right parenthesis ) , Or a single left parenthesis ( , Or an empty string .
- An empty string is also considered a valid string .
Example 1:
Input : "()"
Output : True
Example 2:
Input : "(*)"
Output : True
Example 3:
Input : "(*))"
Output : True
Two 、 Problem solving
Two traversal
Forward and backward traversal , Traverse from left to right , Determine the closing bracket , Traverse from right to left , Determine left parenthesis .
class Solution {
public boolean checkValidString(String s) {
// Two traversal , Forward and backward traversal , First determine whether the left bracket has a corresponding right bracket
int left = 0,cnt = 0;
int length = s.length();
char[] sch = s.toCharArray();
for(char ch : sch){
if(ch == '('){
left++;
}else if(ch == ')'){
left--;
}else{
cnt++;
}
// Judge whether the current left bracket has a corresponding right bracket
if(left < 0){
cnt--;
left++;
}
if(cnt < 0){
return false;
}
}
// Traverse from right to left
int right = 0;
cnt = 0;
for(int i = length-1;i>=0;i--){
char ch = sch[i];
if(ch == ')'){
right++;
}else if(ch == '('){
right--;
}else{
cnt++;
}
// Judge whether the current right bracket has a corresponding left bracket
if(right < 0){
cnt--;
right++;
}
if(cnt < 0){
return false;
}
}
return true;
}
}
Time complexity :O(n)
Spatial complexity :O(1)
greedy
Traversing the string from left to right , During traversal , The number of unmatched left parentheses may change as follows :
If you encounter the left bracket , Then the number of unmatched left parentheses plus 1;
If you encounter the right bracket , You need to have a left bracket and a right bracket match , Therefore, the number of unmatched left parentheses is reduced by 1;
If you encounter an asterisk , Because the asterisk can be regarded as an open bracket 、 Right parenthesis or empty string , Therefore, the number of unmatched left parentheses may be increased by 1、 reduce 1 Or unchanged .
Based on the above conclusion , You can maintain the possible minimum and maximum values of the number of unmatched left parentheses during traversal , Update the minimum and maximum values according to the traversed characters :
If you encounter the left bracket , Then add the minimum and maximum values respectively 1;
If you encounter the right bracket , Then the minimum and maximum values are reduced by 1;
If you encounter an asterisk , Then reduce the minimum value by 1, Add... To the maximum 1.
In any case , The number of unmatched left parentheses must be non negative , So when the maximum becomes negative , No left parenthesis can match the right parenthesis , return false.
When the minimum value is 0 when , The minimum value should not be reduced , To ensure that the minimum value is non negative .
At the end of traversal , All left parentheses should match the right parenthesis , So only if the minimum value is 0 when , character string s Is a valid parenthesis string .
class Solution {
public boolean checkValidString(String s) {
// Greedy Algorithm
// Define two values , Record the maximum and minimum values of the matching left parentheses
int mincnt = 0,maxcnt = 0;
int length = s.length();
char[] sch = s.toCharArray();
for(int i = 0;i<length;i++){
char ch = sch[i];
if(ch == '('){
mincnt++;
maxcnt++;
}else if(ch == ')'){
mincnt = Math.max(mincnt-1,0);
maxcnt--;
if(maxcnt < 0){
return false;
}
}else{
mincnt = Math.max(mincnt - 1,0);
maxcnt++;
}
}
return mincnt == 0;
}
}
Time complexity :O(n)
Spatial complexity :O(1)
边栏推荐
- SQL SERVER2014删除数据库失败,报错偏移量0x0000...
- Kotlin coprocessor scheduling switch threads it's time to unravel the truth
- [laravel] detailed explanation of faker data filling
- CCNP Part XII BGP (IV)
- 亿学学堂帮个人开的证券账户安全吗?是不是有套路
- The "China Mobile Chain" state secret engine was officially launched on BSN
- Zero foundation software testing must see, 10 years of testing old bird's conscience suggestions (a total of 15)
- 新一代云原生数据库的设计与实践
- PHP 字符串与二进制相互转换
- The latest masterpiece of Alibaba, which took 182 days to produce 1015 pages of distributed full stack manual, is so delicious
猜你喜欢
CRC 校驗
程序员都想去国企?技术落后薪资低,躺平几年出来都找不到工作...
全球基金和资管的股票建仓率达到15年内新低
C# 一行代码计算文件的MD5值 - CodePlus系列
The latest masterpiece of Alibaba, which took 182 days to produce 1015 pages of distributed full stack manual, is so delicious
12.Gateway新一代网关
硬件中台项目
Prefabricated dishes usher in the "golden age", who can lead the next trillion market
北汽蓝谷:业绩承压,极狐难期
7-Zip 遭抵制?呼吁者定下“三宗罪”:伪开源、不安全、作者来自俄罗斯!
随机推荐
CSDN's one-stop cloud service is open for internal testing, and new and old users are sincerely invited to grab the fresh
678. 有效的括号字符串
Centos 配置discuz 提示请检查 mysql 模块是否正确加载
Module 9: design e-commerce seckill system
Can you afford to buy a house in Beijing, Shanghai, Guangzhou and Shenzhen with an annual salary of 1million?
How do clients request databases?
In terms of use
Ubuntu系统安装与配置MySQL
I like two men...
C# [字节数组]与[16进制字符串]互相转换 - CodePlus系列
关于#SQL#的问题,如何解决?
新一代云原生数据库的设计与实践
What should I learn in the zero foundation entry test? It's the most comprehensive. Just learn from it
Tearful eyes, it's not easy to change jobs. Three rounds of interviews, four hours of soul torture
程序员都想去国企?技术落后薪资低,躺平几年出来都找不到工作...
The programmer was beaten.
关于OpenCV中图像的widthStep
php 实现抽奖功能
直播管理项目
SQL optimization - in and not in, exist