cjweffort

博客园 首页 联系 订阅 管理

http://ac.jobdu.com/problem.php?cid=1040&pid=25

题目描述:

    在某个字符串(长度不超过100)中有左括号、右括号和大小写字母;规定(与常见的算数式子一样)任何一个左括号都从内到外与在它右边且距离最近的右括号匹配。写一个程序,找到无法匹配的左括号和右括号,输出原来字符串,并在下一行标出不能匹配的括号。不能匹配的左括号用"$"标注,不能匹配的右括号用"?"标注.

输入:

    输入包括多组数据,每组数据一行,包含一个字符串,只包含左右括号和大小写字母,字符串长度不超过100。
    注意:cin.getline(str,100)最多只能输入99个字符!

输出:

    对每组输出数据,输出两行,第一行包含原始输入字符,第二行由"$","?"和空格组成,"$"和"?"表示与之对应的左括号和右括号不能匹配。

样例输入:
)(rttyy())sss)(
样例输出:
)(rttyy())sss)(
?            ?$
// 题目26:括号匹配问题.cpp: 主项目文件。

#include "stdafx.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
using namespace std;

const int N=103;
int flag[N];

typedef struct Node
{
	int index;
	char ch;
}Node;

int main()
{
    //freopen("F:\\test.txt","r",stdin);
    //freopen("F:\\output.txt","w",stdout);
	char str[N];
	while(scanf("%s",str)!=EOF)
	{
		printf("%s\n",str);
		memset(flag,0,sizeof(flag));
		stack<Node> S;
		for(int i=0;str[i];i++)
		{
			if(str[i]=='(')
			{
				Node temp;
				temp.index=i;
				temp.ch='(';
				S.push(temp);
			}
			if(str[i]==')')
			{
				if(S.empty())
				{
					Node temp;
					temp.index=i;
					temp.ch=')';
					S.push(temp);
					continue;
				}
				Node topTemp=S.top();
				if(topTemp.ch=='(')
				{
					S.pop();
				}
				else
				{
					Node temp;
					temp.index=i;
					temp.ch=')';
					S.push(temp);
				}
			}
		}
		while(!S.empty())
		{
			Node temp=S.top();
			if(temp.ch=='(')
				flag[temp.index]=1;
			if(temp.ch==')')
				flag[temp.index]=2;
			S.pop();
		}
		for(int i=0;str[i];i++)
		{
			if(flag[i]==0)
				printf(" ");
			else if(flag[i]==1)
				printf("$");
			else
				printf("?");
		}
		printf("\n");
	}
    return 0;
}


posted on 2013-03-05 11:18  cjweffort  阅读(383)  评论(0编辑  收藏  举报