编写一个将括号添加到开头和结尾以使所有括号匹配并返回的函数

给出一串括号,例如(((())(((),编写一个将括号添加到开头和结尾以使所有括号匹配并返回的函数。

我试图弄清楚如何输出。

输入:)(()(

输出:()(()())

我尝试使用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: `()(()())`
fudandownload 回答:编写一个将括号添加到开头和结尾以使所有括号匹配并返回的函数

每个人我都想通了! @ 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成为局部变量输入

(最终!一个得体的变量!)

本文链接:https://www.f2er.com/3140327.html

大家都在问