要使其在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 虎年幽默搞笑简短祝福语