当前位置:网站首页>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)
边栏推荐
- 预制菜迎来“黄金时代”,谁能领跑下一个万亿市场
- Hardware midrange project
- Can you afford to buy a house in Beijing, Shanghai, Guangzhou and Shenzhen with an annual salary of 1million?
- BSN长话短说之十:如何保证NFT的安全
- In the new database era, don't just learn Oracle and MySQL
- Fried money, lost 10million.
- Can MySQL CDC take out the op field
- 【Laravel 】faker数据填充详解
- Continue to advance, and softcom power steadily promotes cloud intelligence strategy
- What if the win11 account is locked and unable to log in? Win11 account is locked and unable to log in
猜你喜欢

零基础入门测试该学什么?最全整理,照着学就对了

What a high commission! The new programmer's partner plan is coming. Everyone can participate!

全球基金和资管的股票建仓率达到15年内新低

The programmer was beaten.

Wechat emoticons are written into the judgment, and the OK and bomb you send may become "testimony in court"

106. 从中序与后序遍历序列构造二叉树

TC8:UDP_USER_INTERFACE_01-08

Packetdrill script analysis guide

Sleeping second brother...

新数据库时代,不要只学 Oracle、MySQL
随机推荐
项目必用的全局异常处理器,你学会了吗
硬件中台项目
Eat a rich woman's melon...
Which securities company has a low, safe and reliable Commission for stock trading and account opening
678. 有效的括号字符串
SQL SERVER2014删除数据库失败,报错偏移量0x0000...
缺少比较器,运放来救场!(运放当做比较器电路记录)
零基础入行软件测试必看,10年测试老鸟的良心建议(共15条)
What if the win11 account is locked and unable to log in? Win11 account is locked and unable to log in
4hutool实战:DateUtil-格式化时间[通俗易懂]
北汽蓝谷:业绩承压,极狐难期
Win11账号被锁定无法登录怎么办?Win11账号被锁定无法登录
建议收藏 | 在openGauss上遇到慢SQL该怎么办?
How did the data center change from "Britney Spears" to "Mrs. cow"?
Introduction of uniapp wechat applet components on demand
Can MySQL CDC take out the op field
Raspberry pie 4B system construction (ultra detailed version)
数字藏品新一轮热度开启
直播管理项目
持续进阶,软通动力稳步推动云智能战略