是
时间: 2024-02-23 15:58:51 浏览: 11
好的,以下是一份可以在 PTA 上通过括号匹配的 C++ 代码,您可以参考一下:
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool is_match(char ch1, char ch2) {
if (ch1 == '(' && ch2 == ')') return true;
if (ch1 == '[' && ch2 == ']') return true;
if (ch1 == '{' && ch2 == '}') return true;
return false;
}
bool is_balanced(string str) {
stack<char> S;
for (int i = 0; i < str.length(); i++) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
S.push(str[i]);
} else if (str[i] == ')' || str[i] == ']' || str[i] == '}') {
if (S.empty() || !is_match(S.top(), str[i])) {
return false;
}
S.pop();
}
}
return S.empty();
}
int main() {
string str;
getline(cin, str);
if (is_balanced(str)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0;
}
```
在这段代码中,我们使用了一个栈来进行括号匹配的检查。具体来说,对于输入的字符串,我们遍历每个字符,如果遇到左括号则将其入栈,如果遇到右括号则与栈顶元素进行匹配,如果匹配成功则将栈顶元素出栈,否则返回 false。最终,如果栈为空则说明匹配成功,否则说明匹配失败。
您可以将这段代码提交到 PTA 上进行测试,希望能对您有所帮助。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)