Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text;
- /*You are given an expression (string) containing parenthesis and wildcards.
- parenthesis: ( or )
- wildcard: *
- Important : Each wildcard can be regarded as an opening or closing parenthesis, or it can be removed.
- Your tasks is to print yes or no whether an expression containing parenthesis and/or wildcards is valid or not.
- An expression is valid, if:
- The count of opening and closing parenthesis is equal
- Each closing parenthesis must have a corresponding opening parenthesis
- Each opening parenthesis must have a corresponding closing parenthesis
- Opening parenthesis must be on the left side of closing parenthesis
- */
- namespace _13._Validate
- {
- class Program
- {
- static void Main(string[] args)
- {
- int n = int.Parse(Console.ReadLine());
- var sb = new StringBuilder();
- for (int i = 0; i < n; i++)
- {
- string expr = Console.ReadLine();
- if (expr.Length == 0)
- {
- sb.AppendLine("yes");
- continue;
- }
- var output = isExpressionFinallyValid(expr, 0, 0);
- if (output)
- {
- sb.AppendLine("yes");
- }
- else
- {
- sb.AppendLine("no");
- }
- }
- Console.WriteLine(string.Join($"{Environment.NewLine}", sb));
- }
- static bool isExpressionFinallyValid(string expr, int start, int count)
- {
- if (count < 0)
- {
- return false;
- }
- for (int i = start; i < expr.Length; i++)
- {
- if (expr[i] == '(') // (
- {
- count++;
- }
- else if (expr[i] == ')') // )
- {
- if (count <= 0)
- {
- return false;
- }
- count--;
- }
- else if (expr[i] == '*') // *
- {
- bool firstCase = isExpressionFinallyValid(expr, i + 1, count + 1); // (
- if (firstCase)
- {
- return isExpressionFinallyValid(expr, i + 1, count + 1);
- }
- bool secondCase = isExpressionFinallyValid(expr, i + 1, count - 1); // )
- if (secondCase)
- {
- return isExpressionFinallyValid(expr, i + 1, count - 1);
- }
- bool thirdCase = isExpressionFinallyValid(expr, i + 1, count); // nothing
- if (thirdCase)
- {
- return isExpressionFinallyValid(expr, i + 1, count);
- }
- }
- }
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement