【发布时间】:2019-11-08 04:18:48
【问题描述】:
给定一串括号,例如(((())(((),编写一个函数,在开头和结尾加上括号,使所有括号匹配并返回。
我正在尝试弄清楚如何输出它。
输入:)(()(
输出:()(()())
我尝试过使用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: `()(()())`
【问题讨论】:
-
将
n左括号添加到左侧,n右括号添加到右侧。然后添加括号,以使开头和结尾的数量匹配。结果不是最短的,但它是最简单的方法。 -
您可以添加您使用此代码获得的实际输出吗?
-
这是解决简单问题的一种过于复杂的尝试。为什么不边走边平衡?我认为不需要堆栈。 godbolt.org/z/AG-msz
-
@paddy 我没有使用堆栈(它们只是变量名),我再次试图弄清楚如何输出代码中的内容。在 main 函数中输入和输出。
-
它可能是一个向量,但您将它使用作为堆栈。所以我称之为栈。
标签: c++ string vector parentheses