• 921. 使括号有效的最少添加


    921. 使括号有效的最少添加

    Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.

    Formally, a parentheses string is valid if and only if:

    It is the empty string, or
    It can be written as AB (A concatenated with B), where A and B are valid strings, or
    It can be written as (A), where A is a valid string.
    Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

     

    给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的括号( '(' 或是 ')',可以在任何位置),以使得到的括号字符串有效。

    从形式上讲,只有满足下面几点之一,括号字符串才是有效的:

    它是一个空字符串,或者
    它可以被写成 AB (A 与 B 连接), 其中 A 和 B 都是有效字符串,或者
    它可以被写作 (A),其中 A 是有效字符串。
    给定一个括号字符串,返回为使结果字符串有效而必须添加的最少括号数

     

    示例 1:

      输入:"())"
      输出:1
    示例 2:

        输入:"((("
    输出:3
    示例 3:

      输入:"()"
      输出:0
    示例 4:

      输入:"()))(("
      输出:4

     

    #include<iostream>
    #include<bits/stdc++.h>
    #include<cstring>
    using namespace std;
    int minAddToMakeValid(string str) {
        int len=str.length();
        stack<char> st;
        for (int i = 0; i < len; i++)
        {
            if (!st.empty())
            {
                if ((st.top()=='(')&&(str[i]==')'))
                {
                    st.pop();
                }else
                {
                    st.push(str[i]);
                }
            }else
            {
                st.push(str[i]);
            }
        }
        return st.size();
    }
    
    
    int main(){
        string str;
        cin>>str;
        cout<<minAddToMakeValid(str)<<endl;
    }

    方法一: 平衡法
    思路和算法

    保证左右括号数量的 平衡: 计算 '(' 出现的次数减去 ')' 出现的次数。如果值为 0,那就是平衡的,如果小于 0,就要在前面补上缺少的 '('。

    计算 S 每个前缀子数组的 平衡度。如果值是负数(比如说,-1),那就得在前面加上一个 '('。同样的,如果值是正数(比如说,+B),那就得在末尾处加上 B 个 ')' 。

    class Solution {
        public int minAddToMakeValid(String S) {
            int ans = 0, bal = 0;
            for (int i = 0; i < S.length(); ++i) {
                bal += S.charAt(i) == '(' ? 1 : -1;
                // It is guaranteed bal >= -1
                if (bal == -1) {
                    ans++;
                    bal++;
                }
            }
    
            return ans + bal;
        }
    }

     

    因上求缘,果上努力~~~~ 作者:每天卷学习,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/13528630.html

  • 相关阅读:
    LASSO回归原理和Python代码 | 线性回归 | 交叉验证
    初探投行 | 金融
    癌症疫苗 | Cancer Vaccines
    文献复现 | Machine Learning on Human Muscle Transcriptomic Data for Biomarker Discovery and TissueSpecific Drug Target Identification
    癌症研究必备基础知识 | 生信
    初探RNA | RNA分类 | miRNA | lncRNA
    PubMed文献数据挖掘
    罕见病 | 国内 | 国外 | 市场状态
    医保目录谈判 | 国家带量采购 | DRG/DIP支付方式改革 | 腾笼换鸟
    TCGA数据挖掘基本教程
  • 原文地址:https://www.cnblogs.com/BlairGrowing/p/13528630.html
Copyright © 2020-2023  润新知