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