平衡 C++ 中的括號的成本


在本教程中,我們將討論一個程式來查詢平衡括號的成本。

為此,我們將得到一系列括號。我們的任務是透過移動括號一個位置來平衡等式中的這些括號,如果無法平衡,則列印 -1。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int costToBalance(string s) {
   if (s.length() == 0)
      cout << 0 << endl;
   //storing count of opening and
   //closing parentheses
   int ans = 0;
   int o = 0, c = 0;
   for (int i = 0; i < s.length(); i++) {
      if (s[i] == '(')
         o++;
   if (s[i] == ')')
      c++;
   }
   if (o != c)
      return -1;
   int a[s.size()];
   if (s[0] == '(')
      a[0] = 1;
   else
      a[0] = -1;
   if (a[0] < 0)
      ans += abs(a[0]);
   for (int i = 1; i < s.length(); i++) {
      if (s[i] == '(')
         a[i] = a[i - 1] + 1;
      else
         a[i] = a[i - 1] - 1;
      if (a[i] < 0)
         ans += abs(a[i]);
   }
   return ans;
}
int main(){
   string s;
   s = ")))(((";
   cout << costToBalance(s) << endl;
   s = "))((";
   cout << costToBalance(s) << endl;
   return 0;
}

輸出

9
4

更新時間:2020-02-05

89 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.