编写一个函数,在开始和结束处添加括号,使所有括号匹配并返回
Write a function that adds parentheses to the beginning and end to make all parentheses match and return it
给定一个括号字符串,如(((())((()
,编写一个函数,在开头和结尾添加括号,使所有括号匹配并返回。
我正在想办法输出这个。
输入:)(()(
输出:()(()())
我尝试过使用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
成为局部可变输入
(终于!一个名字恰如其分的变量!(
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 在大括号内添加语句会更改代码功能?
- 编写一个函数,在开始和结束处添加括号,使所有括号匹配并返回
- 如何在括号与代码之间添加空格以进行C++?
- 取消脱壳:使用模板在多行类型定义中添加一个尖括号后的新行
- 将错误处理添加到加载数据的函数(但有时还需要使用默认值)
- 配置不稳定以添加括号
- 在什么基础上,由单个元素组成的参数包的折叠表达式被转换为未加括号的表达式
- 如何将文件添加到Android项目中,然后使用NDK加载它
- 在带有'-(inner expression)'的表达式两边添加括号
- 在类名之后但在中括号之前加引号
- 为什么要在hash<int>()(foo)的中间添加额外的括号
- 是否可以将 dll 添加到资源,并使用 LoadLibrary 从资源加载该 dll?C++
- 将缺少的左括号添加到公式中
- gdb:在0x2aaaaaaab000添加的符号文件系统提供的 DSO 中找不到可加载的部分
- 如何在加载数据库时在QTableView中添加QPushButton
- gdb:在添加的符号文件系统提供的编号为0x#的DSO中找不到可加载的节
- 在c++程序中添加不必要的花括号{}是否会减慢速度