【问题标题】:C++ Stack Implementation, checking parenthesis correctnessC++ 栈实现,检查括号的正确性
【发布时间】:2021-12-11 21:28:23
【问题描述】:

我想通过CIN以括号的形式给出表达式,例如:())。然后,通过堆栈的 push & pop 操作,我希望程序打印给我的天气给定的表达式是 BALANCED 还是 NOT。该程序运行良好,但只发现了一个问题,那就是当我输入 ()( 时,它告诉我这个表达式是 IMBALANCED 这很好,但是当我输入 () ( 时,它告诉我这个表达式是 BALANCED,实际上是不平衡的。

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

char Stack[10];
int top=-1;

void push(char ch)
{
    if(top<10)
    {
        top++;
        Stack[top] = ch;
    }
    else
        cout<<"Stack Overflow";
}

void pop()
{
    if(top > -1)
    {
        top--;
    }
    else
        cout<<"Stack Underflow";    
}
int show(){
    cout<<"It is imbalanced.";
}

int main(int argc, char** argv) 
{
    
    int a=0,b=0;
    string exp;
    cout << "Write down the parenthesis:" ;
    cin >> exp;
    bool check = true;
    
    for(int i=0; i<exp.length(); i++)
    {
        if(exp[i]== '(')
        {
            push(exp[i]);
        }
        else if(exp[i]== ')')
        {
            if(top == -1)
            {
                check = false;
                break;
            }
            else
            {
                pop();
            }
        }
    
    }
    
    for(int i=0; i<exp.length(); i++)
    {
        if(exp[i]=='('){
        ++a;
    }
    else if (exp[i]==')')
    {
        b++;
        
        }   
    }
    
    if(a>b){
        cout<<"\n\nGiven Combination is IMBALANCED";
        return 0;
    }
    
    if(check == true)
        cout<<"\n\nGiven Combination is BALANCED";
    
    else
        cout<<"\n\nGiven Combination is IMBALANCED";
    
    
    return 0;
}

【问题讨论】:

  • 你不想检查检查是否为真,堆栈是否为空,看看它是否平衡,否则它是不平衡的。我认为您计数 ( 和 ) 的结束循环不是正确的解决方案。
  • 这个计算不需要栈。
  • 那么,添加一个else 分支以跳过空格。
  • () ( 的错误是 cin &gt;&gt; exp; 请记住,cin &gt;&gt; exp; 会读取到第一个空格字符,因此当您键入 () ( 时,您只会读取平衡的 ()。起初我没有看到,但在这里调试:https://onlinegdb.com/pji0k1cHZS 并在第 50 行放置断点并添加 () ( 作为输入文本后几秒钟内看到它。

标签: c++ data-structures stack push parentheses


【解决方案1】:

主要的 cmets 归结为:

  • 不需要堆栈时不要使用堆栈。
    • 如果您确实使用了一个,请不要将其限制为任意固定深度。
  • 处理错误并报告格式错误的表达式。
  • 确保输入正确; std::getline() 可能比使用 &gt;&gt; 运算符标记化的输入更不容易出错。只需跳过空格(或输入中允许的任何无关紧要的字符)。
  • using namespace std; 是反模式和坏习惯。

基本思想:在遍历字符串时计算嵌套depth。它最终必须为零。它在任何时候都不得降至零以下。

#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include <string_view>

using std::size_t;

bool correctly_parenthesized(std::string_view expression) {
  size_t depth{0};
  for (const auto character : expression) {
    switch (character) {
      case '(': ++depth; break;
      case ')': if (depth) { --depth; break; } else { return false; }
      case ' ': break;
      default: throw std::invalid_argument("invalid character");
    }
  }
  return depth == 0;
}

int main() {
  std::cout << "Write down the parentheses: ";
  std::string exp;
  std::getline(std::cin, exp);
  try {
    std::cout << (correctly_parenthesized(exp) ? "YES" : "NO") << std::endl;
  } catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2019-02-26
    • 2022-06-10
    • 2013-12-08
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多