要使其在C ++中有效的最小括号数
问题陈述
给定一串括号。它可以容纳左括号“(”或右括号“)”。我们必须找到最小括号,以使结果括号字符串有效。
示例
如果str=“(((()”)”,那么我们需要在字符串末尾加上2个右括号,即'))'
算法
计算开括号
计算右括号
必需的括号=abs(开括号的数量–闭括号的数量)
示例
#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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短