目录:
题目要求:
本题要求实现一个函数, 判断一个字符串中括号是否匹配。字符串中的括号包括()、[ ]、{ }。
函数接口定义:
int Match(char code[])
解释接口参数:其中code
是用户传入的参数。code
表示给定的字符串;函数返回1或0,1表示该字符串中括号匹配,0表示该字符串中括号不匹配。
裁判测试程序样例:
#include <iostream>
#include <stack>
using namespace std;
int Match(char code[]); // 要实现的函数
int main()
{
char code[1000];
cin.getline(code,1000);
if (Match(code)) cout << "Yes";
else cout << "No";
return 0;
}
输入样例:
在这里给出一组输入。例如:
for(i=0;i<10;i++) { a[i]=(i+3)%10;}
输出样例:
在这里给出相应的输出。例如:
Yes
代码长度限制 16 KB
时间限制 400 ms
内存限制 64 MB
学习时间:
2022/11/2
- 星期三下午14:00
随便写写的答案:
int Match(char code[])
{
stack<char> st;
int i = 0;
while(code[i]!='\0')
{
if(code[i] == '('||code[i] == '['||code[i] == '{')
st.push(code[i]);
else if(code[i] == ')')
{
if(!st.empty()&&st.top() == '(')
st.pop();
else
return 0;
}
else if(code[i] == '}')
{
if(!st.empty()&& st.top() == '{')
st.pop();
else
return 0;
}
else if(code[i] == ']')
{
if(!st.empty()&& st.top() == '[')
st.pop();
else
return 0;
}
i++;
}
if(st.empty())
return 1;
else
return 0;
}
整体思路:
- 创建一个栈,当遇到"(","{","["其中一种的时候入栈
- 遍历code数组,遇到")","}","]"其中一种的时候同时判断是否和栈顶元素匹配
- 匹配则使栈顶元素出栈
- 反之进栈
- 最后当栈为空栈则表示互相匹配,否则就不匹配