给出一串括号,例如(((())((()
,编写一个将括号添加到开头和结尾以使所有括号匹配并返回的函数。
我试图弄清楚如何输出。
输入:)(()(
输出:()(()())
我尝试使用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: `()(()())`