/*
问题:括号匹配
输入:多组数据,每组一行,一个字符串,只有左右括号和大小写字母,字串长度不超过100
输出:输入胡两行,第一行:源字符串,第二行:有$表示不匹配的左括号,?表示右括号,之间用空格
思路:使用栈,凡是左括号均进栈,凡是遇到右括号,判断栈顶是否是左括号,不是则说明发生错误,记录错误。
输入:)(rttyy())sss)(
输出: )(rttyy())sss)(
? ?$
关键:
1输出不是立即打印出来,而是先缓存在输出的字符数组中
2栈中存放的不应该是'(',而是存放的是字符数组的下标
3由于输入的是字符串,用其大小做限制循环
4给定条件是字符串长度是100,你声明的字符数组长度应该110,比它大
*/
#include <stack>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
/*
int main(int argc,char* argv[])
{
char sStr[100];
while(EOF!=scanf("%s",sStr) && sizeof(sStr) <= 100)
{
printf("%s\n",sStr);
int i = 0;
stack<char> sChar;
//陷入死循环了
while(EOF!=sStr[i] || i <= sizeof(sStr))
{
//遇左括号进栈
if('('==sStr[i])
{
sChar.push(sStr[i]);
}
//遇右括号
else if(')'==sStr[i])
{
//若栈顶是左括号,表示匹配,则栈顶元素出栈,这边要做一个栈是否不为空,才弹出的操作
if(!sChar.empty() && '('==sChar.top())
{
sChar.pop();
}
//若栈顶不是左括号,说明该右括号不能被匹配,则打印“?”
else
{
printf("%c",'?');
}
}
//凡是其他字符,均打印空格
else
{
printf("%c",' ');
}
i++;
}
//如果最后栈不空里面存放的就是未能匹配的左括号
if(!sChar.empty())
{
while(!sChar.empty())
{
printf("%c",'$');
sChar.pop();
}
}
}
getchar();
return 0;
}
*/
int main(int argc,char* argv[])
{
//
char sInput[101];
char sOutput[101];
while(EOF!=scanf("%s",sInput))
{
int i = 0;
stack<int> stackInt;
while('\0'!=sInput[i])
{
if('('==sInput[i])
{
stackInt.push(i);
sOutput[i] = ' ';
}
//else if(')'==sOutput[i])
else if(')'==sInput[i])
{
//如果栈不空,说明,可以找到与右括号匹配的左括号
if(!stackInt.empty())
{
stackInt.pop();
//添加空格' '
sOutput[i] = ' ';
}
//栈空,说明该右括号不能被匹配,则修改相应位置输出为'?'
else
{
sOutput[i] = '?';
}
}
//普通字符输出空格
else
{
sOutput[i] = ' ';
}
i++;
}//while
//如果最后栈不空,则替换相应位置输出为'$'
while(!stackInt.empty())
{
sOutput[stackInt.top()] = '$';
stackInt.pop();
}
//打印原始字符串
printf("%s\n",sInput);
//打印匹配字符串,要手动添加结束符
sOutput[i] = '\0';
printf("%s\n",sOutput);
//printf("%s\n%s\n",sInput,sOutput);
}
system("pause");
getchar();
return 0;
}