当前位置:网站首页>678. 有效的括号字符串
678. 有效的括号字符串
2022-07-01 10:08:00 【hequnwang10】
一、题目描述
给定一个只包含三种字符的字符串:( ,) 和 *,写一个函数来检验这个字符串是否为有效字符串。有效字符串具有如下规则:
- 任何左括号 ( 必须有相应的右括号 )。
- 任何右括号 ) 必须有相应的左括号 ( 。
- 左括号 ( 必须在对应的右括号之前 )。
- 可以被视为单个右括号 ) ,或单个左括号 ( ,或一个空字符串。
- 一个空字符串也被视为有效字符串。
示例 1:
输入: "()"
输出: True
示例 2:
输入: "(*)"
输出: True
示例 3:
输入: "(*))"
输出: True
二、解题
两次遍历
正反遍历,从左往右遍历,确定右括号,从右往左遍历,确定左括号。
class Solution {
public boolean checkValidString(String s) {
//两次遍历,正反遍历,先判断左括号是否有对应的右括号
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++;
}
//判断当前的左括号是否有对应的右括号
if(left < 0){
cnt--;
left++;
}
if(cnt < 0){
return false;
}
}
//从右往左遍历
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++;
}
//判断当前的右括号是否有对应的左括号
if(right < 0){
cnt--;
right++;
}
if(cnt < 0){
return false;
}
}
return true;
}
}
时间复杂度:O(n)
空间复杂度:O(1)
贪心
从左到右遍历字符串,遍历过程中,未匹配的左括号数量可能会出现如下变化:
如果遇到左括号,则未匹配的左括号数量加 1;
如果遇到右括号,则需要有一个左括号和右括号匹配,因此未匹配的左括号数量减 1;
如果遇到星号,由于星号可以看成左括号、右括号或空字符串,因此未匹配的左括号数量可能加 1、减 1 或不变。
基于上述结论,可以在遍历过程中维护未匹配的左括号数量可能的最小值和最大值,根据遍历到的字符更新最小值和最大值:
如果遇到左括号,则将最小值和最大值分别加 1;
如果遇到右括号,则将最小值和最大值分别减 1;
如果遇到星号,则将最小值减 1,将最大值加 1。
任何情况下,未匹配的左括号数量必须非负,因此当最大值变成负数时,说明没有左括号可以和右括号匹配,返回 false。
当最小值为 0 时,不应将最小值继续减少,以确保最小值非负。
遍历结束时,所有的左括号都应和右括号匹配,因此只有当最小值为 0 时,字符串 s 才是有效的括号字符串。
class Solution {
public boolean checkValidString(String s) {
//贪心算法
//定义两个值,记录为匹配的左括号的最大值和最小值
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;
}
}
时间复杂度:O(n)
空间复杂度:O(1)
边栏推荐
- tryhackme圣诞挑战2021-Advent of Cyber 3-day1-IDOR漏洞,不安全的访问控制漏洞
- About database: how to avoid deadlock in gbase 8s
- 树莓派4B系统搭建(超详细版)
- CentOS configures discuz prompt, please check whether the MySQL module is loaded correctly
- Have you learned the necessary global exception handler for the project
- PHP string to binary conversion
- Which securities company has a low, safe and reliable Commission for stock trading and account opening
- Today in history: the semiconductor war in the late 1990s; Von Neumann published the first draft; CBS acquires CNET
- 【黑马早报】俞敏洪称从来不看新东方股价;恒驰5将于7月开启预售;奈雪虚拟股票或涉嫌非法集资;7月1日起冰墩墩停产...
- I like two men...
猜你喜欢

这样理解mmap,挺有意思!

C# 一行代码计算文件的MD5值 - CodePlus系列
![[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](/img/58/8d5c78d919ed60bc833ec4daa22e23.jpg)
[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

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

HMS core audio editing service 3D audio technology helps create an immersive auditory feast

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

【黑马早报】俞敏洪称从来不看新东方股价;恒驰5将于7月开启预售;奈雪虚拟股票或涉嫌非法集资;7月1日起冰墩墩停产...

The stock position building rate of global funds and asset management reached a new low in 15 years

历史上的今天:九十年代末的半导体大战;冯·诺依曼发表第一份草案;CBS 收购 CNET...

Apple amplification! It's done so well
随机推荐
bash: ln: command not found
About widthstep of images in opencv
Can you afford to buy a house in Beijing, Shanghai, Guangzhou and Shenzhen with an annual salary of 1million?
数据中台咋就从“小甜甜”变成了“牛夫人”?
Does anyone know the logic of limit statement execution in Clickhouse? In the picture, the SQL above can be executed successfully
SQL SERVER2014删除数据库失败,报错偏移量0x0000...
Network partition notes
请问有没有人知道clickhouse 中 limit语句执行的逻辑,图片中,上面的SQL可以执行成功
TC8:UDP_USER_INTERFACE_01-08
京东与腾讯续签三年战略合作协议;起薪涨至26万元!韩国三星SK争相加薪留住半导体人才;Firefox 102 发布|极客头条...
Ubuntu system installation and MySQL configuration
Module 9: design e-commerce seckill system
Is it safe to buy funds on the access letter?
线程基础知识
uniapp微信小程序组件按需引入
What should I learn in the zero foundation entry test? It's the most comprehensive. Just learn from it
Voice service notes
我喜欢两个男人。。。
程序员都想去国企?技术落后薪资低,躺平几年出来都找不到工作...
Daily mathematics serial 55: February 24