Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. //Wykorzystując stos napisz metodę sprawdzającą czy wyrażenie ma prawidłowo wpisane nawiasy.
  5. //Przykład:
  6. //"a=)x]i[+5(*y;" - błąd
  7. //"a=(x[i]+5)*y;" - OK
  8. //"a=(x[i)+5]*y;" - błąd
  9. //"a=(x(i]+5]*y;" - błąd
  10. class Program
  11. {
  12. static bool CzyPoprawne(string w)
  13. {
  14. Stack<char> s = new Stack<char>();
  15. for (int i = 0; i < w.Length; i++)
  16. {
  17. if (w[i] == '(' || w[i] == '[') s.Push(w[i]);
  18. if (w[i] == ')')
  19. {
  20. if (s.Count == 0) return false;
  21. if (s.Pop() != '(') return false;
  22. }
  23. if (w[i] == ']')
  24. {
  25. if (s.Count == 0) return false;
  26. if (s.Pop() != '[') return false;
  27. }
  28. }
  29. //powinien stos byc pusty
  30. if (s.Count == 0)
  31. return true;
  32. else
  33. return false;
  34. }
  35. static void Main(string[] args)
  36. {
  37. Console.WriteLine(CzyPoprawne("a=)x]i[+5(*y;"));
  38. Console.WriteLine(CzyPoprawne("a=(x[i]+5)*y;"));
  39. Console.WriteLine(CzyPoprawne("a=(x[i)+5]*y;"));
  40. Console.WriteLine(CzyPoprawne("a=(x(i]+5]*y;"));
  41. Console.ReadKey();
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement