当前位置:网站首页>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)
边栏推荐
- Tearful eyes, it's not easy to change jobs. Three rounds of interviews, four hours of soul torture
- “中移链”国密引擎在BSN正式上线
- Venv: directory structure of venv
- CRC 校驗
- Japanese professor sues Intel FPGA and SOC products for infringing a design patent
- 大佬们,数据湖iceberg的数据,怎样导出到mysql? 有什么工具? sqoop,datax都没
- In terms of use
- Centos 配置discuz 提示请检查 mysql 模块是否正确加载
- [dark horse morning post] Yu Minhong said he never looked at the stock price of New Oriental; Hengchi 5 will start pre-sale in July; Naixue virtual stock or suspected of illegal fund-raising; From Jul
- C# [字节数组]与[16进制字符串]互相转换 - CodePlus系列
猜你喜欢

北汽蓝谷:业绩承压,极狐难期

预制菜迎来“黄金时代”,谁能领跑下一个万亿市场

TC8:UDP_ USER_ INTERFACE_ 01-08

Who's still buying three squirrels
![C [byte array] and [hexadecimal string] mutual conversion - codeplus series](/img/d2/dad88f53701c7cd7638bd4983cbb4b.png)
C [byte array] and [hexadecimal string] mutual conversion - codeplus series

CRC 校驗

【Matytype】在CSDN博客中插入Mathtype行间与行内公式

Meituan P4 carefully collated microservice system architecture design manual to see the world of microservice architecture

谁还在买“三只松鼠”们

The stock position building rate of global funds and asset management reached a new low in 15 years
随机推荐
C [byte array] and [hexadecimal string] mutual conversion - codeplus series
Programmers want to go to state-owned enterprises? The technology is backward and the salary is low. I can't find a job after lying flat for several years
Button button clear border
[laravel] detailed explanation of faker data filling
Is it safe to do fund fixed investment on CICC securities?
Which securities company has a low, safe and reliable Commission for stock trading and account opening
Ubuntu system installation and MySQL configuration
What if the win11 account is locked and unable to log in? Win11 account is locked and unable to log in
Daily mathematics serial 55: February 24
机器学习之线性回归详解
《天天数学》连载55:二月二十四日
SSH服务器拒绝密码,再试一次;PermitRootLogin yes无效问题
谁还在买“三只松鼠”们
SQL optimization - in and not in, exist
这样理解mmap,挺有意思!
STM32 inverter power supply design scheme, based on STM32F103 controller [easy to understand]
How do clients request databases?
Venv: directory structure of venv
推荐一款 JSON 可视化工具神器!
mysql cdc能把能把op字段拿出来吗