要使其在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 送芒果的祝福语简短
18 送给学长毕业祝福语简短