【发布时间】: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;
}
【问题讨论】:
-
您能否更清楚地解释这个问题?您需要该结构做什么?目前代码有什么问题?
-
当当前代码已经运行时,为什么还需要结构体?
-
这就是堆栈的用途。你不会通过使用结构来改进程序。