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;
    }
};
相关推荐
x_xbx21 小时前
LeetCode:739. 每日温度
算法·leetcode·职场和发展
计算机安禾21 小时前
【算法分析与设计】第20篇:图论中的NP困难问题与近似策略
大数据·人工智能·算法
Trouvaille ~21 小时前
【优选算法篇】深入浅出链表算法:交换、重排与合并的终极策略
c++·算法·链表·面试·蓝桥杯·笔试·后端开发
Z_Wonderful1 天前
大文件上传-分片上传-秒传
算法·哈希算法
heimeiyingwang1 天前
【架构实战】分布式ID生成方案:雪花算法与业务ID设计
分布式·算法·架构
圣保罗的大教堂1 天前
leetcode 3121. 统计特殊字母的数量 II 中等
leetcode
圣保罗的大教堂1 天前
leetcode 3120. 统计特殊字母的数量 I 简单
leetcode
sheeta19981 天前
LeetCode 每日一题笔记 日期:2026.05.28 题目:3093. 最长公共后缀查询
linux·笔记·leetcode
SoftLipaRZC1 天前
C语言字符完全指南:字符函数与字符串函数
c语言·开发语言·算法
墨白曦煜1 天前
算法实战笔记:链表的底层逻辑与指针的高阶玩法(二)
笔记·算法·链表