编写一个函数,在开始和结束处添加括号,使所有括号匹配并返回

Write a function that adds parentheses to the beginning and end to make all parentheses match and return it

本文关键字:加括号 添加 返回 结束 一个 开始 函数      更新时间:2023-10-16

给定一个括号字符串,如(((())(((),编写一个函数,在开头和结尾添加括号,使所有括号匹配并返回。

我正在想办法输出这个。

输入:)(()(

输出:()(()())

我尝试过使用cout << pMatch(),但没有得到上面想要的输出。

必须与上述内容相同。非常感谢您的帮助。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
string paranFix(string input) {
string output;
vector<string> strVector;
for (unsigned int a = 0; a < input.size(); ++a) {
if (input[a] == ')') {
if (strVector.empty()) {
output += "(";
}
else {
strVector.pop_back();
}
}
else if (input[a] == '(') {
strVector.push_back(")");
}
output += input[a];
}
while (!strVector.empty()) {
output += strVector.back();
strVector.pop_back();
}
return output;
};
int main(){
string s = "(((())((()"; // Given String
cout << "INPUT: "; // Need to output --> "INPUT: )(()( "
cout << "OUTPUT: "; // Need to output --> "OUTPUT: ()(()()) "
cout << paranFix(s); // This outputs: (((())((())))), which is incorrect
return 0;
}

这就是编译器应该用给定的括号字符串(((())((()输出的内容。

Input: `)(()(`
Output: `()(()())`

我想每个人都明白了@RC0993是第一个指出这一点的人!

string s = (((())((();应为string s = ")(()("; // which is the INPUT;

cout << "INPUT: " << s << endl;
cout << "OUTPUT: " << pMatch(s) << endl;

这里是关于string s = ")(()("; // The Input的输出

INPUT: )(()(
OUTPUT: ()(()())

那只是一个硬编码的输入。

我之所以知道这是因为我追踪了它的使用

它在这里使用cout << paranFix(s); // This outputs: (((())((()))))如果string s = (((())((();

其具有签名string paranFix(string input);

因此,s成为局部可变输入

(终于!一个名字恰如其分的变量!(