LeetCode每日一题(2116. Check if a Parentheses String Can Be Valid)

给定一个括号字符串s和一个锁定字符串locked,长度均为n。如果满足以下条件之一,则认为括号字符串是有效的:它是'()';可以写成AB(A与B连接),其中A和B都是有效的括号字符串;可以写成(A),其中A是一个有效的括号字符串。若在locked为'0'的位置上可以改变s的字符,判断是否能将s变为有效的括号字符串。返回判断结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A parentheses string is a non-empty string consisting only of ‘(’ and ‘)’. It is valid if any of the following conditions is true:

It is ().
It can be written as AB (A concatenated with B), where A and B are valid parentheses strings.
It can be written as (A), where A is a valid parentheses string.
You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0’s and '1’s. For each index i of locked,

If locked[i] is ‘1’, you cannot change s[i].
But if locked[i] is ‘0’, you can change s[i] to either ‘(’ or ‘)’.
Return true if you can make s a valid parentheses string. Otherwise, return false.

Example 1:

Input: s = “))()))”, locked = “010100”
Output: true

Explanation: locked[1] == ‘1’ and locked[3] == ‘1’, so we cannot change s[1] or s[3].
We change s[0] and s[4] to ‘(’ while leaving s[2] and s[5] unchanged to make s valid.

Example 2:

Input: s = “()()”, locked = “0000”
Output: true

Explanation: We do not need to make any changes because s is already valid.

Example 3:

Input: s = “)”, locked = “0”
Output: false

Explanation: locked permits us to change s[0].
Changing s[0] to either ‘(’ or ‘)’ will not make s valid.

Constraints:

  • n == s.length == locked.length
  • 1 <= n <= 105
  • s[i] is either ‘(’ or ‘)’.
  • locked[i] is either ‘0’ or ‘1’.

从左向右,分别计数 open, close 和 wild(locked==‘0’)的数量, wild 一定要能补偿 close-open 的差值, 否则必定非法。
从右向左,同样的计数, wild 一定要能补偿 open-close 的差值, 否则必定非法



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值