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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP