hdu 4915 Parenthese sequence

Problem Description
bobo found an ancient string. The string contains only three charaters – “(”, “)” and “?”.

bobo would like to replace each “?” with “(” or “)” so that the string is valid (defined as follows). Check if the way of replacement can be uniquely determined.

Note:

An empty string is valid.
If S is valid, (S) is valid.
If U,V are valid, UV is valid.

Input
The input consists of several tests. For each tests:

A string s1s2…sn (1≤n≤106).

Output
For each tests:

If there is unique valid string, print “Unique”. If there are no valid strings at all, print “None”. Otherwise, print “Many”.

Sample Input
??
???
(??

Sample Output
Unique
Many
None

贪心思想,思路借鉴:https://blog.csdn.net/The_star_is_at/article/details/69525793

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;
char str[1000006];
char tmp[1000006];
bool judge(int len)
{
	stack<char> st;
	for(int i=0;i<len;i++){
		if(tmp[i]=='('){
			st.push(tmp[i]);
		}
		else{
			if(st.empty()) return false;
			st.pop();
		}
	}
	if(!st.empty())
		return false;
	return true;
}
int main()
{
	while(scanf("%s",&str)!=EOF)
	{
		int len=strlen(str);
		if(len&1){
			printf("None\n");
			continue;
		}
		int l=0,r=0;
		for(int i=0;i<len;i++){
			if(str[i]=='(') l++;
			if(str[i]==')') r++;
		}
		int lenl=(len-2*l)/2;//多少个问号会变成左括号 
		int lenr=(len-2*r)/2;//多少个问号会变成右括号 
		int xl=-1,xr=-1;
		for(int i=0;i<len;i++){
			if(str[i]=='?'){
				if(lenl>0){
					tmp[i]='(';
					lenl--;
					if(lenl==0) xl=i;
				}
				else{
					tmp[i]=')';
					if(xr==-1) xr=i;
				}
			}
			else{
				tmp[i]=str[i];
			}
		}
		if(!judge(len))
			printf("None\n");
		else{
			if(xl==-1||xr==-1) 
				printf("Unique\n");
			else{
				char s=tmp[xl];tmp[xl]=tmp[xr];tmp[xr]=s;
				if(!judge(len))
					printf("Unique\n");
				else
					printf("Many\n");
			}
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值