Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. using System;
  2.  
  3. namespace ValidBrackets
  4. {
  5. class Program
  6. {
  7. static void TestResult(string expected, string actual)
  8. {
  9. if (expected != actual)
  10. throw new Exception($"Wrong answer, expected {expected}, got {actual}");
  11. }
  12. static void Main(string[] args)
  13. {
  14. try
  15. {
  16. TestResult("valid", Validate("()()()()()"));
  17. TestResult("invalid", Validate(")("));
  18. TestResult("invalid", Validate("(((**"));
  19. TestResult("valid", Validate("*"));
  20. TestResult("valid", Validate(""));
  21. TestResult("valid", Validate("***"));
  22. TestResult("valid", Validate("**"));
  23. TestResult("valid", Validate("(**)"));
  24. TestResult("valid", Validate("****))"));
  25.  
  26. Console.WriteLine("All pass");
  27. }
  28. catch (Exception e)
  29. {
  30. Console.WriteLine(e.Message);
  31. }
  32. }
  33.  
  34. static string Validate(string brackets)
  35. => Validate(brackets, 0, 0) ? "valid" : "invalid";
  36.  
  37. // Increment bracketsChecker when we see an '(' and decrement when we see a ')'.
  38. static bool Validate(string brackets, int index, int bracketsChecker)
  39. {
  40. if (index == brackets.Length)
  41. {
  42. // at the end of the string, if the checker is zero, then brackets match
  43. return bracketsChecker == 0;
  44. }
  45.  
  46. return brackets[index] switch
  47. {
  48. '(' => Validate(brackets, index + 1, bracketsChecker + 1),
  49.  
  50. // When we see a ')' it's important to validate that there was a '(' before it.
  51. // Otherwise, ')(' would be considered valid
  52. // 'bracketsChecker > 0' asserts that
  53. ')' => bracketsChecker > 0 && Validate(brackets, index + 1, bracketsChecker - 1),
  54.  
  55. // use conditional ||, if one of the three returns true, then we have a valid option
  56. '*' => Validate(brackets, index + 1, bracketsChecker + 1) || // treat * as (
  57. Validate(brackets, index + 1, bracketsChecker) || // treat * as nothing
  58. Validate(brackets, index + 1, bracketsChecker - 1), // treat * as )
  59.  
  60. _ => throw new Exception("Wrong symbol")
  61. };
  62. }
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement