1. 程式人生 > >【Regular Expression】【HihoCoder - 1110】(思維規律)

【Regular Expression】【HihoCoder - 1110】(思維規律)

題目:

Your task is to judge whether the input is a legal regular expression.

 A regular expression is defined as follow:

 1: 0 and 1 are both regular expressions.

 2: If P and Q are regular expressions, PQ is a regular expression.

 3: If P is a regular expression, (P) is a regular expression.

 4: If P is a regular expression, P* is a regular expression.

 5: If P and Q are regular expressions, P|Q is a regular expression.

Input

The input contains multiple testcases.

 Each test case is a single line with a string not containing space.The length of the string is less than 100.

Output

For each testcase, print yes if the input is a regular expression, otherwise print no.

Sample Input

010101101*
(11|0*)*
)*111

Sample Output

yes
yes
no

解題報告:這道題目就是已知合法的正則表示式,然後又有* | ( )等符號,需要繼續判斷操作後的正則表示式是否還是合法的。因為( )這倆需要有匹配的現象,還有 | 能夠覆蓋掉 | 前邊的數字,根據這些就可以寫出程式碼了。

ac程式碼:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;

const int maxn =1e3+10;

char str[maxn];

int main()
{
	while(scanf("%s",str)!=EOF)
	{
		int flag=0,intflag=0;//intflag是判斷符號前邊是否存在數字,主要是為()準備的
		char c=str[0];
		int i=0;
		int cnt=0;
		while(c!='\0'&&c!='\n')
		{
			if(c=='(')
			{
				cnt++;
				intflag=0;
			}
			else if(c==')')
			{
				if(!intflag)
				{
					flag=1;
					break;
				}
				cnt--;
			}
			if(cnt<0)
			{
				flag=1;
				break;
			}
			if(c=='0'||c=='1')
			{
				intflag=1;
			}
			if(c=='*'&&!intflag)
			{
				flag=1;
				break;
			}
			if(c=='|')
			{
				if(!intflag)
				{
					flag=1;
					break;
				}
				intflag=0;
			}
			c=str[++i];
		}
		if(cnt!=0) flag=1;
		if(flag)
			printf("no\n");
		else
			printf("yes\n");
		
	}
	return 0;	
}