Advertisement
nassss

Untitled

Mar 16th, 2020
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.02 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. /*You are given an expression (string) containing parenthesis and wildcards.
  4. parenthesis: ( or )
  5. wildcard: *
  6.  
  7. Important : Each wildcard can be regarded as an opening or closing parenthesis, or it can be removed.
  8.  
  9. Your tasks is to print yes or no whether an expression containing parenthesis and/or wildcards is valid or not.
  10.  
  11. An expression is valid, if:
  12.  
  13. The count of opening and closing parenthesis is equal
  14. Each closing parenthesis must have a corresponding opening parenthesis
  15. Each opening parenthesis must have a corresponding closing parenthesis
  16. Opening parenthesis must be on the left side of closing parenthesis
  17. */
  18.  
  19. namespace _13._Validate
  20. {
  21. class Program
  22. {
  23. static void Main(string[] args)
  24. {
  25. int n = int.Parse(Console.ReadLine());
  26. var sb = new StringBuilder();
  27. for (int i = 0; i < n; i++)
  28. {
  29. string expr = Console.ReadLine();
  30. if (expr.Length == 0)
  31. {
  32. sb.AppendLine("yes");
  33. continue;
  34. }
  35. var output = isExpressionFinallyValid(expr, 0, 0);
  36. if (output)
  37. {
  38. sb.AppendLine("yes");
  39. }
  40. else
  41. {
  42. sb.AppendLine("no");
  43. }
  44. }
  45. Console.WriteLine(string.Join($"{Environment.NewLine}", sb));
  46. }
  47. static bool isExpressionFinallyValid(string expr, int start, int count)
  48. {
  49. if (count < 0)
  50. {
  51. return false;
  52. }
  53. for (int i = start; i < expr.Length; i++)
  54. {
  55. if (expr[i] == '(') // (
  56. {
  57. count++;
  58. }
  59. else if (expr[i] == ')') // )
  60. {
  61. if (count <= 0)
  62. {
  63. return false;
  64. }
  65. count--;
  66. }
  67. else if (expr[i] == '*') // *
  68. {
  69. bool firstCase = isExpressionFinallyValid(expr, i + 1, count + 1); // (
  70. if (firstCase)
  71. {
  72. return isExpressionFinallyValid(expr, i + 1, count + 1);
  73. }
  74. bool secondCase = isExpressionFinallyValid(expr, i + 1, count - 1); // )
  75. if (secondCase)
  76. {
  77. return isExpressionFinallyValid(expr, i + 1, count - 1);
  78. }
  79. bool thirdCase = isExpressionFinallyValid(expr, i + 1, count); // nothing
  80. if (thirdCase)
  81. {
  82. return isExpressionFinallyValid(expr, i + 1, count);
  83. }
  84. }
  85. }
  86. return true;
  87. }
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement