【问题标题】:Write a function that adds parentheses to the beginning and end to make all parentheses match and return it编写一个函数,在开头和结尾添加括号,使所有括号匹配并返回
【发布时间】: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


【解决方案1】:

每个人我想我都明白了! @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 &lt;&lt; paranFix(s); // This outputs: (((())((())))) 如果string s = (((())((();

签名为string paranFix(string input);

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

(终于!一个名副其实的变量!)

【讨论】:

  • 很高兴您能够解决它,但我仍然不确定出了什么问题以及如何解决。也许尝试更清楚地阐述你的想法/问题,更清楚地说明 what做了what期望得到了什么,以便这里的其他用户可以帮助弄清楚发生了什么错误很明显......
猜你喜欢
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 2018-07-11
  • 1970-01-01
相关资源
最近更新 更多