【问题标题】:C ++: Check if the order of parentheses and brackets in a string is balanced using structureC ++:使用结构检查字符串中括号和括号的顺序是否平衡
【发布时间】:2021-06-05 15:43:04
【问题描述】:

我需要验证表达式是平衡的,它具有完全相同数量的括号,并且对于方括号和键的打开和关闭顺序是否正确,例如“{[(()]}”。但是,我的堆栈需要一个结构体,但我不知道该怎么做。你能帮帮我吗?这段代码可以工作,但我需要使用结构体而不是字符串。

#include <iostream>
#include <stack>
using namespace std;

bool checkExpress(string str){
    int i;
    stack <char> st;

    if(str.length() % 2 != 0) return false;

    for(auto ch : str){

        if (ch == '('  ch == '[') {
            st.push(ch);
        } else if(ch == ')') {
            if(st.empty()  st.top() != '(') return false;
            st.pop();
        } else if(ch == ']') {
            if(st.empty() || st.top() != '[') return false;
            st.pop();
        } 
    }

    return true;
}


int main(){
    string a = "(([[]]))";

    if(checkExpress(a)) cout << "The expression is well constructed.";
    else cout << "The expression is not well constructed.";

    return 0;
}
#include <iostream>
#include <stack>
using namespace std;

bool checkExpress(string str){
    int i;
    stack <char> st;

    if(str.length() % 2 != 0) return false;

    for(char ch : str){
    if (ch == '(' || ch == '[') {
    st.push(ch);
    continue;
    }
    if (st.empty())
      return false;
    char top = st.top();
    st.pop();

    if (top == '(' && ch==')')
      continue; // we good
    if (top == '[' && ch==']')
      continue; // we good

    return false; // invalid character, or bad match
}
    return true;
}


int main(){
    string a = "(([[]]))";

    if(checkExpress(a)) cout << "The expression is well constructed.";
    else cout << "The expression is not well constructed.";

    return 0;
}

【问题讨论】:

  • 您能否更清楚地解释这个问题?您需要该结构做什么?目前代码有什么问题?
  • 当当前代码已经运行时,为什么还需要结构体?
  • 这就是堆栈的用途。你不会通过使用结构来改进程序。

标签: c++ struct stack


【解决方案1】:

我会推荐使用链表

struct Node { 
    char data; 
    struct Node* next; 
};

如果下一个是 "{[(" delete on "}])" 之一,则可以添加

【讨论】:

    【解决方案2】:

    因为这看起来像是一个练习,所以我不会在这里放代码,而是尝试描述一个可能对你有帮助的思考过程。

    输入字符串有效的条件是每个括号/括号必须有一个相应的结束字符并且顺序必须匹配。您可以在使用 帮助程序堆栈 读取输入字符串时检查这两个条件(任何允许您在顶部添加和删除元素的数据结构都可以,因此堆栈是自然的选择)。

    • 读取输入字符串,每次找到左括号/方括号时,将其添加到堆栈中。您只会将开始字符添加到堆栈中。
    • 每次遇到结束字符时,都应尝试删除堆栈顶部的字符
      • 但前提是它是您当前从输入字符串中读取的结束字符的相应开始字符。如果不是,则顺序错误并且输入字符串无效。如果在读取结束字符时堆栈为空,则意味着结束字符多于开始字符​​li>
      • 如果你读完输入字符串并且堆栈为空,那么输入字符串是有效的,否则意味着你缺少一些结束字符(如果你读完输入字符串时堆栈不为空)

    请注意,如果您的输入是堆栈而不是字符串,它不会改变您需要执行的操作。但是,在这种情况下,您将反向阅读所有内容,因为使用堆栈您只能访问顶部的元素。在这种情况下,您可以更改流程以将结束字符添加到 帮助程序堆栈。也就是说,现在当您读取输入堆栈时,只要找到结束字符,就将其添加到 helper 堆栈 中,并且每当找到开始字符时,您都会尝试从 中删除相应的结束字符辅助堆栈

    【讨论】:

      猜你喜欢
      • 2018-06-23
      • 1970-01-01
      • 2022-08-13
      • 2021-09-20
      • 2011-11-04
      • 2017-03-07
      • 2019-01-12
      • 2013-12-28
      相关资源
      最近更新 更多