用算符优先分析算法判断表达式是否合法的c++代码
时间: 2023-08-14 18:02:09 浏览: 92
以下是用算符优先分析算法判断表达式是否合法的C++代码示例:
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// 定义运算符的优先级
int getPriority(char op) {
if (op == '*' || op == '/')
return 2;
else if (op == '+' || op == '-')
return 1;
else
return 0;
}
// 判断字符是否为运算符
bool isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
// 判断表达式是否合法
bool isValidExpression(string expression) {
stack<char> opStack;
int i = 0;
while (i < expression.length()) {
char ch = expression[i];
if (ch == '(')
opStack.push(ch);
else if (ch == ')') {
if (opStack.empty() || opStack.top() != '(')
return false;
opStack.pop();
} else if (isOperator(ch)) {
if (opStack.empty() || getPriority(ch) > getPriority(opStack.top()))
opStack.push(ch);
else {
while (!opStack.empty() && getPriority(ch) <= getPriority(opStack.top())) {
opStack.pop();
}
opStack.push(ch);
}
}
i++;
}
return opStack.empty();
}
int main() {
string exp1 = "2+3*4";
string exp2 = "(2+3)*4";
string exp3 = "2+3*(4+5)";
string exp4 = "2+3*4)";
string exp5 = "2+3*4(";
cout << exp1 << " is " << (isValidExpression(exp1) ? "valid" : "invalid") << endl;
cout << exp2 << " is " << (isValidExpression(exp2) ? "valid" : "invalid") << endl;
cout << exp3 << " is " << (isValidExpression(exp3) ? "valid" : "invalid") << endl;
cout << exp4 << " is " << (isValidExpression(exp4) ? "valid" : "invalid") << endl;
cout << exp5 << " is " << (isValidExpression(exp5) ? "valid" : "invalid") << endl;
return 0;
}
```
该程序中,我们使用了一个操作符栈来存储运算符,遇到左括号时将其压入栈中,遇到右括号时将栈中的元素弹出直到遇到左括号。如果栈为空或栈顶的运算符优先级低于当前运算符,则将当前运算符压入栈中;否则,将栈中的运算符弹出直到栈为空或栈顶的运算符优先级低于当前运算符,然后将当前运算符压入栈中。最后,如果操作符栈为空,则表达式合法,否则表达式不合法。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)