2 条题解

  • 1
    @ 2023-11-2 9:36:51

    从左到右遍历字符串每一个字符,若

    1. 当前字符为’(’,则将当前字符加入栈中。
    2. 当前字符为’)’,则看栈是否为空,若不为空,则说明存在’(’可以和当前字符匹配,弹出栈顶元素;若为空,则当前的右括号没有办法进行匹配,必须把它修改为’(’并入栈,同时让修改次数+1。

    遍历完成后,最终答案还需要加上栈中的元素个数/2,因为此时栈中的元素均为左括号,需要把其中的一半修改为右括号。

    #include<bits/stdc++.h>
    using namespace std;
    const int N=1e5+5;
    char s[N];
    char sta[N];
    int l,top,ans;
    int main(){
    	cin>>s+1;
    	l=strlen(s+1);
    	for (int i=1;i<=l;++i)
    		if (s[i]=='(') sta[++top]='(';
    		else if (!top) ans++,sta[++top]='(';
    		else --top;
    	cout<<ans+top/2;
    }
    
    
    • 0
      @ 2024-4-6 9:40:17

      题解中有用手搓栈做的了,我就提供一个用STL栈做的吧。

      思路可以去看其他的题解,我这里就提供一种不同的做法。

      AC code:

      #include<bits/stdc++.h>
      #define ll long long
      using namespace std;
      string s;
      stack<char> sta;
      ll cnt;
      int main(){
          cin>>s;
          for(ll i=0;i<s.length();i++)
              if(s[i]=='(')
                  sta.push('(');
              else if(!sta.empty())
                  sta.pop();
              else
                  sta.push('('),cnt++;
          printf("%lld",cnt+(sta.size()>>1));
          return 0;
      }
      
      • 1

      信息

      ID
      536
      时间
      1000ms
      内存
      125MiB
      难度
      3
      标签
      递交数
      128
      已通过
      72
      上传者