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;
    }
};
相关推荐
起名字真南2 分钟前
【OJ题解】C++实现字符串大数相乘:无BigInteger库的字符串乘积解决方案
开发语言·c++·leetcode
lucy153027510792 分钟前
【青牛科技】GC5931:工业风扇驱动芯片的卓越替代者
人工智能·科技·单片机·嵌入式硬件·算法·机器学习
杜杜的man18 分钟前
【go从零单排】迭代器(Iterators)
开发语言·算法·golang
小沈熬夜秃头中୧⍤⃝35 分钟前
【贪心算法】No.1---贪心算法(1)
算法·贪心算法
木向1 小时前
leetcode92:反转链表||
数据结构·c++·算法·leetcode·链表
阿阿越1 小时前
算法每日练 -- 双指针篇(持续更新中)
数据结构·c++·算法
skaiuijing1 小时前
Sparrow系列拓展篇:对调度层进行抽象并引入IPC机制信号量
c语言·算法·操作系统·调度算法·操作系统内核
Star Patrick2 小时前
算法训练(leetcode)二刷第十九天 | *39. 组合总和、*40. 组合总和 II、*131. 分割回文串
python·算法·leetcode
武子康3 小时前
大数据-214 数据挖掘 机器学习理论 - KMeans Python 实现 算法验证 sklearn n_clusters labels
大数据·人工智能·python·深度学习·算法·机器学习·数据挖掘
m0_571957586 小时前
Java | Leetcode Java题解之第543题二叉树的直径
java·leetcode·题解