【问题标题】:Matching the same symbols using stack in c++在c ++中使用堆栈匹配相同的符号
【发布时间】:2017-10-31 00:38:38
【问题描述】:

所以我的任务是关于平衡符号,而不是 () 例如它是 ~~ 而对于 {} 它是 ^^,基本上符号应该匹配。 ,有人可以帮忙吗?

举个例子

 BinarySearchTree~~: root ^ nullptr ^
    ^
    ^
this should return true

这是我写的函数

bool balanced(std::string expression)

{
    int i;

    std::stack<char>check;

    char symbol;

    for (i=0; i<expression.length();i++)
    {
        symbol=expression[i];
        if(symbol=="~" || symbol=="^")
        {
            check.push(symbol);
        }
        if(check.empty())
              return false;
         else
              check.pop();
    }

    if(check.empty())
        return true;
}

【问题讨论】:

标签: c++ string algorithm stack


【解决方案1】:

你的意思好像是下面这个

bool balanced(const std::string &expression)
{
    std::stack<char> check;

    for (std::string::size_type i = 0; i < expression.size(); i++)
    {
        char c = expression[i];

        if (c == '~' || c == '^')
        {
            if (!check.empty() && check.top() == c)
            {
                check.pop();
            }
            else
            {
                check.push(c);
            }
        }
    }

    return check.empty();
}

考虑到这样的字符串

"~^~^"

结果将是错误的。但是当一对符号包含在另一对符号中时,例如

"~^^~"

结果为真。

【讨论】:

  • 我明白了。非常感谢。现在很有意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
相关资源
最近更新 更多