Leetcode 1541. Minimum Insertions to Balance a Parentheses String (括号问题好题)

  1. Minimum Insertions to Balance a Parentheses String
    Medium

Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:

Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.

Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.

In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.

For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced.

You can insert the characters '(' and ')' at any position of the string to balance it if needed.

Return the minimum number of insertions needed to make s balanced.

Example 1:

Input: s = "(()))"

Output: 1

Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced.

Example 2:

Input: s = "())"

Output: 0

Explanation: The string is already balanced.

Example 3:

Input: s = "))())("

Output: 3

Explanation: Add '(' to match the first '))', Add '))' to match the last '('.

Constraints:

1 <= s.length <= 105

s consists of '(' and ')' only.

解法1:这题其实不简单。关键是来了左括号时,当前所需有括号数目是偶数的处理。

注意:

  1. 当来了'('括号时,
    a. 如果当前所需右括号数目rightNeeded是偶数,那没什么大关系,再把rightNeeded +2就可以。比如输入"(())",rightNeeded=2,那再来一个'(',rightNeeded=4。
    b. 如果当前所需右括号数目rightNeeded是奇数,那么比较麻烦,我们必须在新来左括号'('的时候消掉一个多余的右括号,这样,rightNeeded就是偶数,跟a的情况一样。怎么消掉呢?那我们再增加左括号,消掉一个右括号就可以了。
    比如输入"(()",rightNeeded=3。再来一个'(',此时我们必须在这个新来的'('前面加上一个'(',即"((()(",这样,leftNeeded++, rightNeeded--,就可以把rightNeeded变成偶数了。

举例:

"(()))(()))()())))"

cpp 复制代码
class Solution {
public:
    int minInsertions(string s) {
        int n = s.size();
        int leftNeeded = 0, rightNeeded = 0;
        for (auto c : s) {
            if (c == '(') {
                if (rightNeeded & 0x1) {
                    leftNeeded++;
                    rightNeeded--;
                }
                rightNeeded += 2;

            } else {
                rightNeeded--;
                if (rightNeeded == -1) {
                    leftNeeded++;
                    rightNeeded = 1;
                }               
            }
        }               
        return leftNeeded + rightNeeded;
    }
};
相关推荐
Dizzy.5174 分钟前
数据结构(查找)
数据结构·学习·算法
hello_simon1 小时前
【Word转PDF】在线Doc/Docx转换为PDF格式 免费在线转换 功能强大好用
职场和发展·pdf·word·学习方法·word转pdf·石墨文档·word转换
分别努力读书3 小时前
acm培训 part 7
算法·图论
武乐乐~3 小时前
欢乐力扣:赎金信
算法·leetcode·职场和发展
'Debug3 小时前
算法从0到100之【专题一】- 双指针第一练(数组划分、数组分块)
算法
Fansv5873 小时前
深度学习-2.机械学习基础
人工智能·经验分享·python·深度学习·算法·机器学习
测试19984 小时前
接口测试工具:Postman
自动化测试·软件测试·python·测试工具·职场和发展·接口测试·postman
yatingliu20195 小时前
代码随想录算法训练营第六天| 242.有效的字母异位词 、349. 两个数组的交集、202. 快乐数 、1. 两数之和
c++·算法
uhakadotcom5 小时前
Google DeepMind最近发布了SigLIP 2
人工智能·算法·架构
sjsjs115 小时前
【数据结构-并查集】力扣1202. 交换字符串中的元素
数据结构·leetcode·并查集