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
题解:标记判断走一遍即可,详见代码
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=110;
char s[N];
int main()
{
while(~scanf("%s", s+1)) {
int len = strlen(s + 1);
int flag = 1;
int z = 0,f = 0;// z 表示 出现了几次左括号, f 代表前面连续的符号成立了吗
for(int i = 1; i <= len; i++) {
if(s[i] == '0' || s[i] == '1') {
f = 1;
} else if(s[i] == '(') {
z++;
f = 0;// 遇见左括号 成立中断
} else if(s[i] == ')') {
if(z==0 || f==0) flag = 0; // 没有左括号 或者 前面没有连续符合的
z--;
f = 1;
} else if(s[i] == '*') {
if(f == 0) flag = 0; // 前面没有连续符合的
f = 1;
} else if(s[i] == '|') {
if(f == 0) flag = 0; // 前面没有连续符合的
f = 0; // 遇见|| 成立中断
} else flag = 0;
}
if(z != 0) flag = 0; //括号不为0
if(f==0) flag = 0; // 前面连续符号不符合
printf(flag ? "yes\n" : "no\n");
}
return 0;
}