使用c++和栈,判断表达式重点括号是否匹配。输入表达式加以验证。
时间: 2024-06-13 08:05:26 浏览: 8
判断表达式中括号是否匹配是一个经典的栈的应用。具体实现方法如下:
1. 遍历表达式中的每个字符,如果是左括号(包括小括号、中括号和大括号),则将其压入栈中。
2. 如果是右括号,则判断栈顶元素是否与之匹配,如果匹配则将栈顶元素弹出,否则表达式不合法。
3. 遍历完整个表达式后,如果栈为空,则表达式合法,否则表达式不合法。
下面是代码实现:
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isMatch(char left, char right) {
return (left == '(' && right == ')') || (left == '[' && right == ']') || (left == '{' && right == '}');
}
bool isValid(string s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (st.empty() || !isMatch(st.top(), c)) {
return false;
}
st.pop();
}
}
return st.empty();
}
int main() {
string s;
cout << "请输入表达式:" << endl;
cin >> s;
if (isValid(s)) {
cout << "表达式合法" << endl;
} else {
cout << "表达式不合法" << endl;
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)