括号匹配代码用switch语句
时间: 2024-05-19 11:09:21 浏览: 16
括号匹配代码是一种常见的算法问题,可以用switch语句实现。下面是一个简单的示例代码:
```
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
string s;
stack<char> st;
cout << "请输入要检查的字符串:" << endl;
cin >> s;
for (int i = 0; i < s.size(); i++) {
switch(s[i]) {
case '(':
case '[':
case '{':
st.push(s[i]);
break;
case ')':
if (st.empty() || st.top() != '(') {
cout << "不匹配" << endl;
return 0;
} else {
st.pop();
break;
}
case ']':
if (st.empty() || st.top() != '[') {
cout << "不匹配" << endl;
return 0;
} else {
st.pop();
break;
}
case '}':
if (st.empty() || st.top() != '{') {
cout << "不匹配" << endl;
return 0;
} else {
st.pop();
break;
}
default:
break;
}
}
if (st.empty()) {
cout << "匹配" << endl;
} else {
cout << "不匹配" << endl;
}
return 0;
}
```
该代码使用了一个栈来存储左括号,遇到左括号时入栈,遇到右括号时从栈顶弹出左括号并进行匹配。如果最终栈为空,则说明所有括号都匹配,否则说明有未匹配的括号。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)