您的位置:首页 > 其它

括号匹配

2016-01-25 12:08 204 查看
转自王道机试指南

#include <stdio.h>
#include <stack>

using namespace std;

stack<int> s;
char str[110];//保存输入的字符串
char ans[110];//保存输出的字符串

int main()
{
while(scanf("%s",str) != EOF)
{
int i;
for(i = 0;str[i] != 0;++i)
{
if(str[i] == '(')
{
s.push(i);
ans[i] = ' ';
}
else if(str[i] == ')')
{
if(s.empty() == false)
{
s.pop();
ans[i] = ' ';
}
else
ans[i] = '?';
}
else
ans[i] = ' ';
}
while(!s.empty())
{
ans[s.top()] = '$';
s.pop();
}
ans[i] = 0;
puts(str);
puts(ans);
}
return 0;
}


本题是考察堆栈的利用,利用模板类,需要包含堆栈头文件#include<stack>,必须包含命名空间using namespace std;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: