C++中新增最小數量的括號使其有效


問題陳述

給定一個括號字串。它可以包含左括號‘(‘或右括號’)’。我們必須找到使結果括號字串有效的最小括號數。

示例

如果 str = “((()” 則在字串末尾需要 2 個右括號,即‘))’

演算法

  • 計算左括號數
  • 計算右括號數
  • 所需括號 = 絕對值(左括號數 - 右括號數)

示例

#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int requiredParentheses(string str) {
   int openingParentheses = 0, closingParentheses = 0;
   for (int i = 0; i < str.length(); ++i) {
      if (str[i] == '(') {
         ++openingParentheses;
      } else if (str[i] == ')') {
         ++closingParentheses;
      }
   }
   return abs(openingParentheses - closingParentheses);
}
int main() {
   string str = "((()";
   cout << "Required parentheses = " << requiredParentheses(str) << endl;
   return 0;
}

當您編譯並執行以上程式時。它生成以下輸出 −

Required parentheses = 2

更新於:2019 年 11 月 22 日

263 次瀏覽

職業生涯新起點

完成課程,獲得認證

開始
廣告
© . All rights reserved.