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;
    }
};
相关推荐
瓦力wow35 分钟前
c语言 写一个五子棋
c语言·c++·算法
X-future42635 分钟前
院校机试刷题第六天:1134矩阵翻转、1052学生成绩管理、1409对称矩阵
线性代数·算法·矩阵
Codeking__1 小时前
前缀和——中心数组下标
数据结构·算法
爱喝热水的呀哈喽1 小时前
非线性1无修
算法
花火QWQ2 小时前
图论模板(部分)
c语言·数据结构·c++·算法·图论
Pacify_The_North2 小时前
【进程控制二】进程替换和bash解释器
linux·c语言·开发语言·算法·ubuntu·centos·bash
轮到我狗叫了2 小时前
力扣310.最小高度树(拓扑排序,无向图),力扣.加油站力扣.矩阵置零力扣.二叉树中的最大路径和
算法·leetcode·职场和发展
埃菲尔铁塔_CV算法2 小时前
深度学习驱动下的目标检测技术:原理、算法与应用创新(二)
深度学习·算法·目标检测
wuqingshun3141592 小时前
经典算法 (A/B) mod C
c语言·开发语言·c++·算法·蓝桥杯
白杆杆红伞伞2 小时前
04_决策树
算法·决策树·机器学习