假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序随意 但需要成对出现。即([ ]())或[([][])]等为正确的格式,[(])或([())或(() 221224严2年 为不正确的格式。 给定一串括号输入(换行作为结束符),检测格式是否正确,若正确输出 YES;错误输出 NO。【样例输入】([]()) 【样例输出】 YES 用C++实现
时间: 2024-04-16 18:23:46 浏览: 22
以下是使用C++实现检测括号格式的示例代码:
```cpp
#include <iostream>
#include <stack>
#include <string>
bool checkBrackets(const std::string& input_str) {
std::stack<char> bracketStack;
for (char c : input_str) {
if (c == '(' || c == '[') {
bracketStack.push(c);
} else if (c == ')' || c == ']') {
if (bracketStack.empty()) {
return false;
}
char top = bracketStack.top();
if ((c == ')' && top == '(') || (c == ']' && top == '[')) {
bracketStack.pop();
} else {
return false;
}
}
}
return bracketStack.empty();
}
int main() {
std::string input_str;
std::getline(std::cin, input_str);
bool result = checkBrackets(input_str);
if (result) {
std::cout << "YES" << std::endl;
} else {
std::cout << "NO" << std::endl;
}
return 0;
}
```
你可以将以上代码保存为一个名为`bracket_check.cpp`的文件,并使用C++编译器进行编译,然后运行生成的可执行文件。输入"([]())",输出应为"YES"。
注意:在C++中,需要包含`<iostream>`、`<stack>`和`<string>`头文件,并使用`std::stack`表示栈。使用`std::getline(std::cin, input_str)`来读取多行输入。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)