CodeForces - 612C Replace To Make Regular Bracket Sequence

题目链接:http://codeforces.com/problemset/problem/612/C

You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.

The following definition of a regular bracket sequence is well-known, so you can be familiar with it.

Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.

For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.

Determine the least number of replaces to make the string s RBS.

Input

The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.

Output

If it's impossible to get RBS from s print Impossible.

Otherwise print the least number of replaces needed to get RBS from s.

Example
Input
[<}){}
Output
2
Input
{()}[]
Output
0
Input
]]
Output
Impossible


题目大意:括号匹配。给出一个括号序列,要求替换括号使其成为合法的匹配序列(注意: 有两种类型的括号, 替换仅在相同类型间进行),输出最少的替换个数,如果无法替换使其序列合法,则输出“impossible”。
思路一:
1.当左括号和右括号数目不等时:该序列不合法,输出“impossible”。遍历序列,遇左括号进栈,遇右括号对栈顶元素进行判断。
2.当左右括号数目相等时,用栈进行判断。遍历序列:遇左括号进栈;遇右括号判断栈顶元素,若不匹配则替换次数+1,不管匹配与否,栈顶元素都出栈。
3.存在左右括号数目相等,但括号序列不匹配的情况。例如:(()))(。这个是我在写代码时没有考虑到的一点。针对这点,只需加一个判断,遇到右括号而栈为空即不匹配。
思路二:
用栈判断,遍历序列。遇左括号进栈,遇右括号判断栈顶元素,三种情况:
1.栈顶元素与该右括号匹配,栈顶元素出栈。
2.栈顶元素与该右括号不匹配,替换次数+1,栈顶元素出栈。
3.栈为空,该序列不合法,输出“impossible”
总结:思路二较思路一更为简洁,避免了左右括号的统计及思路一中第三点情况的判断。
下面给出的代码是思路一的代码(思路二是大佬的题解)
#include<iostream>
#include<map>
#include<stack>
using namespace std;

int main()
{
	string c;
	cin>>c;
	int i,b(0);
	int l(0),r(0);
	for (i=0;i<c.length();i++)
	  if (c[i]=='(' || c[i]=='[' || c[i]=='{' || c[i]=='<') l++;
	  else r++;
	if (l!=r) cout<<"Impossible"<<endl;
	else 
	{
		stack<char> s;
		int a(0);
		map<char,char> m;
		m[')']='(';m[']']='[';m['}']='{';m['>']='<';
		for (i=0;i<c.length();i++)
		  if (c[i]=='(' || c[i]=='[' || c[i]=='{' || c[i]=='<')
		    s.push(c[i]);
		  else if (s.empty()) b=1;
		  else if (s.top()==m[c[i]]) s.pop();
		  else a++,s.pop();
		if (b) cout<<"Impossible"<<endl;
		else if (a) cout<<a<<endl;
		else cout<<0<<endl;
	}
	return 0;
 } 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值